问题描述
我正在开发使用Spotify API的React应用程序,我不知道为什么尝试通过API的PKCE OAuth流获取访问令牌时会出现此错误。
{
error: "unsupported_grant_type",error_description: "grant_type parameter is missing"
}
我严格按照guide的指示进行操作,因此可以很好地获取身份验证代码。这是我尝试获取令牌的电话。
let res = await axios.post("https://accounts.spotify.com/api/token",{},{
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},params: {
"grant_type": "authorization_code","code": data.code,"redirect_uri": redirectUri,"code_verifier": verifier,"client_id": clientId
}
}).catch(err => console.error(err));
我尝试过将参数传递到post请求的主体中,并作为url参数传递,两者都产生相同的结果。如您所见,我清楚地提供了grant_type
,并且使用了指南所说的值。
解决方法
使用 querystring npm 包解析数据,因为我们在标题中使用 application/x-www-form-urlencoded
并将 grant_type 更改为 grant_type: "client_credentials"
var querystring = require('querystring');
const headers = {
headers: {
"Content-Type": "application/x-www-form-urlencoded",}
};
let data = {
grant_type: "client_credentials",code: data.code,redirectUri: "http://localhost:8000/callback",client_id: your_client_id,client_secret: your_client_secret,};
我们使用 query.stringify() 作为 data 因为内容类型是 application/x-www-form-urlencoded 也不使用参数,因为它是发布请求
axios
.post(
"https://accounts.spotify.com/api/token",querystring.stringify(data),headers
)
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
});
,
您是否已跟踪消息并验证请求正文是否确实符合预期?您的OAuth字段看起来完全正确,因此我怀疑这可能只是axios语法问题。
我可能是错的,但应将“ params”字段称为“ data”,例如this class of mine。