簡體   English   中英

從 lambda 函數調用 Spotify API

[英]Invoking Spotify API from lambda function

我需要從 Spotify API 獲取數據,然后將響應發送到前端。 為了避免 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 

標頭是:

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": ""
}

而且我不知道如何將數據發送回前端。 您有任何指導來實現我正在尋找的東西嗎?

編輯:我也嘗試按照建議使用 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)"
  ]
}

感謝@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);
    });
};

試試這個


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;

};

希望這可以幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM