access token
. 首先,我从Spotify获取授权代码,然后将其发送到生成
访问令牌
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
我没有添加所有的代码,但它工作得很好。归还的是
访问令牌
refresh token
.
Hapi.js
所以我把这个放在
pre
处理程序并发送
访问令牌
访问令牌
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
未处理的PromisejectionWarning:错误:请求失败,状态代码401
看来我的
访问令牌
可能无效。这是我唯一能想到的,但是,我检查了,我发送的令牌与第一个函数生成的相同,所以它应该是有效的。也许我格式化请求的方式是错误的。我搞不懂这是什么原因。