【问题标题】:"invalid_grant" error while trying to use Discord's oauth2尝试使用 Discord 的 oauth2 时出现“invalid_grant”错误
【发布时间】:2021-04-11 18:12:13
【问题描述】:
const response = await fetch(`https://discordapp.com/api/oauth2/token`, {
  method: "POST",
  headers: {
    "Content-Type": "application/x-www-form-urlencoded",
  },
  body: JSON.stringify({
    client_id: process.env.CLIENT_ID,
    client_secret: process.env.CLIENT_SECRET,
    redirect_uri: redirectURL,
    grant_type: 'authorization_code',
    code: code,
  }),
});

当我运行上面的代码时,它返回{ error: 'invalid_grant' },我不知道为什么。有什么解决办法吗?谢谢。

【问题讨论】:

    标签: javascript oauth-2.0 discord


    【解决方案1】:

    您是否还需要按照文档发送范围参数:

    const data = {
    
            client_id: 'your client id',
            client_secret: 'your client secret',
            grant_type: 'authorization_code',
            redirect_uri: 'your redirect uri',
            code: accessCode,
            scope: 'the scopes',
        };
        
        fetch('https://discord.com/api/oauth2/token', {
            method: 'POST',
            body: new URLSearchParams(data),
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
        })
            .then(res => res.json())
            .then(console.log);
    

    您需要将您的正文作为 URLSearchParams(data) 发送。

    您还需要在代码顶部添加以下内容:

    const fetch = require('node-fetch');
    

    检查这个新链接:

    https://discordjs.guide/oauth2/#oauth2-flows

    【讨论】:

    • 我通过了范围,但仍然无济于事。 sourceb.in/PRFno2AVqi
    • 和之前一样的错误,{ error: 'invalid_grant' }
    • 我修复了它,我所要做的就是使用查询字符串而不是 JSON。
    【解决方案2】:

    我修复了它,我所要做的就是使用 querystring 而不是 JSON。

    【讨论】:

      猜你喜欢
      • 2021-09-11
      • 2015-12-08
      • 2021-11-07
      • 1970-01-01
      • 1970-01-01
      • 2018-05-14
      • 2017-07-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多