【问题标题】:Request to get user info from Spotify Web API results in 401 error请求从 Spotify Web API 获取用户信息导致 401 错误
【发布时间】:2019-03-18 06:22:14
【问题描述】:

我想使用 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 发送到另一个处理程序/函数,然后使用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:错误:请求失败,状态码为 401

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

【问题讨论】:

    标签: node.js oauth-2.0 axios spotify hapijs


    【解决方案1】:

    您在 axios.get 请求中有小错字。将标题更改为标题

    改变

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

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

    【讨论】:

    • 天啊,这个问题真的不值得我花这么多时间在它上面。谢谢!
    • 同意,我们都会犯这种愚蠢的错误 :) 它有时会发生。干杯
    猜你喜欢
    • 2019-11-08
    • 1970-01-01
    • 2022-01-10
    • 2018-06-07
    • 1970-01-01
    • 1970-01-01
    • 2015-11-28
    • 1970-01-01
    • 2021-08-08
    相关资源
    最近更新 更多