尝试从不和谐 API 获取访问令牌时'unsupported_grant_type'



所以我试图实现Discord登录到我的网站,但当我试图用代码从https://discord.com/api/oauth2/token交换访问令牌时,我只得到了{ error: 'unsupported_grant_type' }

我的代码:

const tokenResponseData = await request('https://discord.com/api/oauth2/token', {
method: 'POST',
data: JSON.stringify({
client_id: config.clientId,
client_secret: config.clientSecret,
code: code,
grant_type: 'authorization_code',
redirect_uri: `http://localhost:3000/api/auth`,
scope: 'identify',
}),
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
});

我已经挣扎了一段时间了,所以任何帮助都会很棒!

根据Discord GitHub上的这个问题,当你的身体格式不正确时,就会发生这种情况。

经过一番挖掘,我在SO上看到了这篇文章,这让我相信你应该使用URLSearchParams,而不是字符串化你的json数据。

let params = new URLSearchParams();
params.append('client_id', config.clientId);
params.append('client_secret', config.clientSecret);
params.append('code', code);
params.append('grant_type', 'authorization_code');
params.append('redirect_uri', `http://localhost:3000/api/auth`);
params.append('scope', 'identify');
const tokenResponseData = await request(
'https://discord.com/api/oauth2/token',
{
method: 'POST',
data: params,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
);

原来我做错了。我需要将请求参数格式化为类似URL查询的格式,并在POST请求的正文中作为字符串发送。

const tokenResponseData = await fetch(
`https://discord.com/api/oauth2/token`,
{
method: 'POST',
body: `client_id=${encodeURIComponent(`${config.clientId}`)}&client_secret=${encodeURIComponent(`${config.clientSecret}`)}&grant_type=authorization_code&code=${code}&redirect_uri=${encodeURIComponent(`http://localhost:3000/api/auth`)}`,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
);

相关内容

最新更新