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

如何解决Discord OAuth2返回'Invalid "code" in request'错误?

Discord OAuth2 "Invalid 'code' in request" 错误排查与解决

以下是针对该错误的具体排查和解决步骤:

  • code为一次性凭证:Discord的authorization code只能使用一次,无论之前请求成功与否,用过就会失效,必须重新引导用户授权获取新的code。
  • 严格匹配redirect_uri:确保请求token时的redirect_uri和授权环节填写的完全一致,包括协议(http/https)、域名、端口、路径,哪怕是末尾的斜杠差异都可能触发验证失败。
  • 检查参数编码与实际发送内容:在代码中打印最终生成的请求body字符串,确认code没有被错误编码。可修改代码添加日志:
    const params = new URLSearchParams({
        grant_type: "authorization_code",
        code: code,
        redirect_uri: redirectURI,
        client_id: process.env.DISCORD_CLIENT_ID as string,
        client_secret: process.env.DISCORD_CLIENT_SECRET as string,
        scope: 'identify email'
    })
    console.log(params.toString())
    const response = await fetch(`https://discord.com/api/oauth2/token`, {
        method: "POST",
        headers: {
            "Content-Type": "application/x-www-form-urlencoded"
        },
        body: params.toString()
    })
    
    查看打印内容,确认code及其他字段均正确无误。
  • 验证环境变量有效性:确认process.env.DISCORD_CLIENT_ID和process.env.DISCORD_CLIENT_SECRET已正确加载,不存在空值或错误值。可在请求前添加console.log(process.env.DISCORD_CLIENT_ID, process.env.DISCORD_CLIENT_SECRET)验证。
  • 排除网络干扰:若应用部署在有代理、防火墙的环境中,请求可能被篡改导致参数异常。可尝试在本地无代理环境测试请求,确认是否为网络层面问题。
  • 确认scope完全一致:授权时用户同意的scope必须与请求token时的scope完全匹配,不能有增减,比如授权时请求了identify email,请求token时就不能只传identify。

你的原始请求代码

const response = await fetch(`https://discord.com/api/oauth2/token`, {
    method: "POST",
    headers: {
        "Content-Type": "application/x-www-form-urlencoded"
    },
    body: new URLSearchParams({
        grant_type: "authorization_code",
        code: code,
        redirect_uri: redirectURI,
        client_id: process.env.DISCORD_CLIENT_ID as string,
        client_secret: process.env.DISCORD_CLIENT_SECRET as string,
        scope: 'identify email'
    }).toString()
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 01:08:37