You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

实现Discord登录调用OAuth2接口获access token遇unsupported_grant_type错误

Discord OAuth2 换取Access Token时出现unsupported_grant_type错误的解决办法

你的问题核心是请求头与请求体格式不匹配:你指定了Content-Type: application/x-www-form-urlencoded,但却用JSON.stringify()把请求体转为了JSON格式,Discord的token接口无法识别这种矛盾的请求格式,因此返回错误。

以下是两种可行的修复方案:

方案一:使用表单编码格式的请求体(推荐)

保持application/x-www-form-urlencoded的请求头,将请求体转为表单编码格式:

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

方案二:改用JSON格式请求体

将请求头改为application/json,保持JSON格式的请求体(Discord接口支持此方式):

const tokenResponseData = await request('https://discord.com/api/oauth2/token', {
    method: 'POST',
    data: {
        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/json',
    },
});

额外注意事项

  • 确保redirect_uri与Discord开发者平台中配置的授权回调地址完全一致,包括协议(http/https)、域名、端口和路径
  • 检查grant_type拼写正确,必须是authorization_code
  • 确认client_id和client_secret没有复制错误或遗漏

内容的提问来源于stack exchange,提问作者SirGolem

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 11:25:25