【发布时间】: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 token 和refresh 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