访问 Node.JS Post 请求的响应

Access the response of Node.JS Post Request

我正在尝试围绕 Spotify API 的客户端凭证流程进行思考,在他们的文档中,他们有这种方法来获取访问令牌:

var client_id = 'CLIENT_ID';
var client_secret = 'CLIENT_SECRET';

const authOptions = {
  url: "https://accounts.spotify.com/api/token",
  headers: {
    "Authorization":
      "Basic " +
      new Buffer.from(clientID + ":" + clientSecret).toString("base64"),
    "Content-Type": "application/x-www-form-urlencoded",
  },
  form: {
    grant_type: "client_credentials",
  },
  json: true,
};

request.post(authOptions, function(error, response, body) {
  if (!error && response.statusCode === 200) {
    var token = body.access_token;
  }
});

现在我正在尝试获取 token 并在 API 调用中导出或使​​用它,但无论我做什么,我都无法访问该语句。

将 POST 放入变量或函数并调用它会导致 undefined

这就是我要实现的目标:

import authOptions from "./credentials.js";
import pkg from "request";
const { post } = pkg;

const Spotify = {
  getAccessToken() {
    post(authOptions, function (error, response, body) {
      if (!error && response.statusCode === 200) {
        const token = body.access_token;
        return token;
      }
    });
  },

  async search(input) {
    const accessToken = Spotify.getAccessToken();
    const response = await fetch(
      `https://api.spotify.com/v1/search?q=${input}&type=artist`,
      {
        headers: {
          "Authorization": `Bearer ${accessToken}`,
          "Content-Type": "application/json",
        },
      }
    );
    const data = await response.json();
    console.log(data);
  },
};

export default Spotify;

当然,post 请求没有返回访问令牌。

有什么方法可以将那段代码转换成 Async/Await

您可以创建一个新的承诺:

async function getAccessToken(){
    return new Promise((resolve, reject) => {
        post(authOptions, function (error, response, body) {
            if(error){
                reject(error);
            } else if (response.statusCode === 200) {
                const token = body.access_token;
                resolve(token);
            }
         });
    });
};

resolve/reject 允许您在调用回调时 return 该值,并将错误传递给调用者进行处理。您可以使用这种格式来承诺任何基于回调的函数,方法是在承诺内部调用它并使用 resolve/reject 到 return 值。