router.get('/spotifyLogin', (req,res) => {
const state = generateRandomString(16);
const scope = 'user-read-recently-played';
const queryParams = querystring.stringify({
response_type: 'code',
client_id: client_id,
scope: scope,
redirect_uri: redirect_uri,
state: state
});
res.redirect(`https://accounts.spotify.com/authorize?${queryParams}`);
});
router.get('/callback', (req,res) => {
const authorizationCode = req.query.code || null;
const state = req.query.state || null;
axios({
method: 'post',
url: 'https://accounts.spotify.com/api/token',
data: querystring.stringify({
grant_type: 'authorization_code',
code: authorizationCode,
redirect_uri: redirect_uri,
}),
headers: {
'content-type': 'application/x-www-form-urlencoded',
Authorization: `Basic ${new Buffer.from(`${client_id}:${client_secret}`).toString('base64')}`,
},
})
.then(response => {
if (response.status === 200) {
res.send(response.data)
} else {
res.send(response);
}
})
.catch(error => {
res.send(error);
});
});
我正在自定义 express api 服务器上执行 spotify 授权代码流 https://developer.spotify.com/documentation/general/guides/authorization/code-flow/
当我向 token url 发出发布请求时,我应该在我的 response.data 中得到一个 json 对象,但我得到了奇怪的字符 Screenshot of response.data
最佳答案
为 axios 请求将 accept-encoding
header 设置为 *
为我解决了这个问题。
在您的情况下,应该看起来像这样:
axios({
method: 'post',
url: 'https://accounts.spotify.com/api/token',
data: querystring.stringify({
grant_type: 'authorization_code',
code: authorizationCode,
redirect_uri: redirect_uri,
}),
headers: {
'content-type': 'application/x-www-form-urlencoded',
Authorization: `Basic ${new Buffer.from(`${client_id}:${client_secret}`).toString('base64')}`,
'accept-encoding': '*'
},
})
关于node.js - axios response.data 奇怪的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74623066/