Discord Oauth2 访问令牌“不支持授予类型无”

2024-03-27

我正在尝试为我的用 Express 制作的网站制作一个不和谐的登录系统。我创建了一个函数来获取访问令牌,以便我可以在路由中使用该函数。

我试图从以下位置获取访问令牌:https://discord.com/api/oauth2/token https://discord.com/api/oauth2/token

这是我的代码:

    async GetToken(code) {
        let access_token;
        const payload = {
            'client_id': client_id,
            'client_secret': client_secret,
            'grant_type': 'authorization_code',
            'code': code,
            'redirect_uri': redirect_uri,
            'scope': scope,
        };
        const config = {
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        };
        fetch(discord_token_url, {
            method: 'post',
            body: payload,
            headers: config.headers,
        }).then(response => response.json()).then(json => console.log(json)).catch(err => console.log(err));
        return access_token;
    },

这是我得到的错误:

{
  error: 'unsupported_grant_type',
  error_description: 'Grant type None is not supported'
}

正如您所看到的,我已经给出了正确的授权类型,但我收到了此错误。


忘记更新以添加解决方案,看到很多人都在看这个,所以这里是解决方案(感谢@Kira): 你必须使用URL搜索参数 https://www.npmjs.com/package/node-fetch#post-with-form-parameters

// Modules
const fetch = require('node-fetch');
const { url } = require('inspector');
const { URLSearchParams } = require('url');

// Add the parameters
const params = new URLSearchParams();
params.append('client_id', client_id);
params.append('client_secret', client_secret);
params.append('grant_type', 'authorization_code');
params.append('code', code);
params.append('redirect_uri', redirect_uri);
params.append('scope', scope);

// Send the request
fetch('https://discord.com/api/oauth2/token', {
  method: 'post',
  body: params,
  headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json' },
}).then(r => r.json()).then(Response => {
  // Handle it...
  handle()
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Discord Oauth2 访问令牌“不支持授予类型无” 的相关文章

随机推荐