从 lambda 函数调用 Spotify API

Invoking Spotify API from lambda function

我需要从 Spotify API 获取数据,然后将响应发送到 front-end。为了避免 CORS 问题并向 Spotify 隐藏密钥和机密,我想使用 Lambda 进行 API 调用,然后发回响应。更准确地说我的申请:

1. FrontEnd > API Gateway
2. API Gateway > Lambda
3. Lambda > Spotify API (request their API to get token)
4. Spotify API > Lambda (token in the response)
5. Lambda > API Gateway
6. API Gateway > FrontEnd

Spotify 端点是:

https://accounts.spotify.com/api/token?grant_type=client_credentials 

Header 是:

Content-Type: 'application/x-www-form-urlencoded'
Authorization: 'Basic XXX'

到目前为止,我能够使用 Lambda 函数执行此操作:

const https = require('https');
exports.handler = async (event, context) => {

    return new Promise((resolve, reject) => {
        const options = {
          hostname: 'accounts.spotify.com',
          path: '/api/token?grant_type=client_credentials',
          method: 'POST',
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Authorization': 'Basic XXX'
          }
        }

        const req = https.request(options, (res) => {
          res.on('data', function (chunk) {
            console.log('BODY: ' + chunk);
          });
          resolve('Success');
        });

        req.on('error', (e) => {
          reject(e.message);
        });

        // send the request
        req.write('');
        req.end();
    });
};

但是我无法从 API:

得到回应
{
    "access_token": "YYY",
    "token_type": "Bearer",
    "expires_in": 3600,
    "scope": ""
}

而且我不知道如何将数据发送回 front-end。您有任何指导来实现我正在寻找的东西吗?

编辑:我也尝试按照建议使用 axios:

const axios = require("axios");

module.exports.handler = (event, context, callback) => {
    const headers = {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Authorization': 'Basic XXX'
          }
    axios.post('https://accounts.spotify.com/api/token?grant_type=client_credentials', {}, {
      headers: headers
    })
    .then(function(response) {
        console.log(response)
        callback(null, response);
    })
    .catch(function(err) {
       console.error("Error: " + err);
       callback(err);
    });
};

但出现以下错误:

Response:
{
  "errorType": "Error",
  "errorMessage": "Request failed with status code 400",
  "trace": [
    "Error: Request failed with status code 400",
    "    at createError (/var/task/node_modules/axios/lib/core/createError.js:16:15)",
    "    at settle (/var/task/node_modules/axios/lib/core/settle.js:17:12)",
    "    at IncomingMessage.handleStreamEnd (/var/task/node_modules/axios/lib/adapters/http.js:237:11)",
    "    at IncomingMessage.emit (events.js:215:7)",
    "    at endReadableNT (_stream_readable.js:1183:12)",
    "    at processTicksAndRejections (internal/process/task_queues.js:80:21)"
  ]
}

试试这个


const https = require('https');
function hitApi() {
  return new Promise((resolve, reject) => {
    const options = {
      hostname: 'accounts.spotify.com',
      path: '/api/token?grant_type=client_credentials',
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': 'Basic XXX'
      }
    }
    https.request(options, (res) => {
      res.setEncoding("utf8");
      let body = "";
      res.on('data', function (chunk) {
        body += chunk;
      });
      res.on("error", err => {
        reject(err);
      });

      res.on('end', function () {
        resolve(body);
      });
    });
  });
}

exports.handler = async (event, context) => {

  const result = await hitApi();
  return result;

};

希望这对您有所帮助

感谢@jarmod 和@Ashish Modi,下面的解决方案对我有用:

const axios = require("axios");
const querystring = require('querystring');

module.exports.handler = (event, context, callback) => {
    const headers = {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Authorization': 'Basic XXX'
          }
    axios.post('https://accounts.spotify.com/api/token?grant_type=client_credentials', querystring.stringify({}), {
      headers: headers
    })
    .then(function(response) {
        const res = {
        statusCode: 200,
        body: (response.data.access_token)
    };
        callback(null, res);
    })
    .catch(function(err) {
       console.error("Error: " + err);
       callback(err);
    });
};