请求从 Spotify Web API 获取用户信息导致 401 错误

Request to get user info from Spotify Web API results in 401 error

我想使用 Spotify API 来检索用户信息。我已经想出一个 access token。首先,我从 Spotify 获得授权码,然后将其发送到生成 access token 的端点,这看起来是这样...

const access = async (req, h) => {

// URL to retrieve an access token.
const spotify_url = "https://accounts.spotify.com/api/token";

// Send authorization code to spotify.
const response = await axios({
  method: "post",
  url: spotify_url,
  params: {
    grant_type: "authorization_code",
    code: req.query.auth_code,
    redirect_uri: process.env.REDIRECT_URI
  },
  headers: {
    "Content-Type": "application/x-www-form-urlencoded",
    "Authorization": "Basic " + (Buffer.from(process.env.CLIENT_ID + ":" + process.env.CLIENT_SECRET).toString("base64"))
  }
})
.then(response => {

  // Retrieve access and refresh tokens.
  let access_token = response.data.access_token;
  let response_token = response.data.refresh_token

  return {
    access_token: access_token,
    response_token: response_token
  }

})
...
...
return result

我没有添加所有代码,但它运行良好。返回的是 access tokenrefresh token.

我正在使用 Hapi.js 所以我将其放入 pre 处理程序并将 access token 发送到另一个 handler/function 然后使用 access token检索用户信息...

const user_account = async (access_token) => {

  const user = await axios.get("https://api.spotify.com/v1/me", {
    header: {
      "Authorization": "Bearer " + access_token
    }
  })
  .then(response => {

    // Return the full details of the user.
    return response;

  })
  .catch(err => {
    throw Boom.badRequest(err);
  });

  return user;
}

问题是我收到 401 错误。

UnhandledPromiseRejectionWarning: Error: Request failed with status code 401

看来我的access token可能无效。这是我唯一能想到的,但是,我检查过并发送了第一个函数生成的相同令牌,所以它应该是有效的。也许我格式化我的请求的方式是错误的。我想不通这是什么原因。

您在 axios.get 请求中有小的拼写错误。将 header 更改为 headers

改变

 header: {
  "Authorization": "Bearer " + access_token
}

 headers: {
  "Authorization": "Bearer " + access_token
}