我正在尝试使用 Node.js 应用程序访问 Spotify Web API。我已将 grant_type
指定为 authorization_code
,但收到 unsupported_grant_type
错误,其描述为 grant_type 必须是 client_credentials、authorization_code 或 refresh_token
。
据我所知,我的 post
请求格式正确且值均正确。不确定还需要检查什么。
app.post('/auth', (req, res)=>{
const auth = Buffer
.from(`${process.env.CLIENT_ID}:${process.env.CLIENT_SECRET}`)
.toString('base64');
axios.post(token_uri, {}, {
params: {
'grant_type': 'authorization_code',
'code': req.body.code,
'redirect_uri': redirect_uri,
client_id: process.env.CLIENT_ID,
client_secret: process.env.CLIENT_SECRET
}, headers: {
'Authorization': `Basic ${auth}`,
'Content-Type':'application/x-www-form-urlencoded'
}
})
.then(res=>{
console.log(res.data)
})
.catch(err=>{
console.log(err)
})
})
最佳答案
您正确设置了内容类型,但您以 JSON 格式而不是 x-www-form-urlencoded 格式发送数据。
以下 JSON 格式
params: {
'grant_type': 'authorization_code',
'code': 'my_secret_code
}
可以像这样转换为 x-www-form-urlencoded:
params = 'grant_type=authorization_code&code=my_secret_code'
尝试像这样更新您的请求:
const params = 'grant_type=authorization_code&code=' + req.body.code
+ '&redirect_uri=' + redirect_uri
+ '&client_id=' + process.env.CLIENT_ID
+ '&client_secret=' + process.env.CLIENT_SECRET';
axios.post(token_uri,
params,
{
headers: {
'Authorization': `Basic ${auth}`,
'Content-Type':'application/x-www-form-urlencoded'
}
})
.then(res=>{
console.log(res.data)
})
.catch(err=>{
console.log(err)
})
关于node.js - Spotify API 授权代码流程返回 'unsupported_grant_type' 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49801190/