400从Discord API请求令牌时出错



我正在尝试使用Discord的API创建一个登录过程。根据文档,我假设使用回调URL上返回的code进行另一次调用以接收访问令牌。我已经按照这里的说明做了。然而,我在打电话时一直收到400错误。

我需要纠正的地方有什么帮助吗?

let options = {
method: 'POST',
headers: {
'Authorization': 'Basic ' + discordInfo.client_id + ":" + discordInfo.client_secret,
'Content-Type': 'application/x-www-form-urlencoded'
},
data: {
'client_id': discordInfo.client_id,
'client_secret': discordInfo.client_secret,
'grant_type': 'authorization_code',
'code': req.query.code,
'redirect_uri': discordInfo.callbackUrl,
'scope': 'identify email'
}
}
let discord_data = await fetch('https://discord.com/api/oauth2/token', options).then((response) => {
if (response.status >= 400) {
throw new Error("Bad response from server");
}
return response.json();
}).then((response) => {
console.log('Discord Response', response);
}).catch((error) => {
console.log(error);
});

经过进一步研究,我发现了以下视频,这对我有所帮助。

这是工作代码:

let options = {
url: 'https://discord.com/api/oauth2/token',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: new URLSearchParams({
'client_id': discordInfo.client_id,
'client_secret': discordInfo.client_secret,
'grant_type': 'client_credentials',
'code': req.query.code,
'redirect_uri': discordInfo.callbackUrl,
'scope': 'identify email'
})
}
let discord_data = await fetch('https://discord.com/api/oauth2/token', options).then((response) => {
return response.json();
}).then((response) => {
return response;
});

最新更新