首页 > 解决方案 > 从 Discord API 请求令牌时出现 400 错误

问题描述

我正在尝试使用 Discord 的 API 创建登录过程。根据文档,我假设使用code回调 URL 上的返回来进行另一个调用以接收访问令牌。我已按照此处的说明进行操作。400但是,我在拨打电话时一直收到错误消息。

关于我需要纠正的任何帮助?

let options = {
  method: 'POST',
  headers: {
    'Authorization': 'Basic ' + discordInfo.client_id + ":" + discordInfo.client_secret,
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  data: {
    'client_id': discordInfo.client_id,
    'client_secret': discordInfo.client_secret,
    'grant_type': 'authorization_code',
    'code': req.query.code,
    'redirect_uri': discordInfo.callbackUrl,
    'scope': 'identify email'
  }
}

let discord_data = await fetch('https://discord.com/api/oauth2/token', options).then((response) => {
  if (response.status >= 400) {
    throw new Error("Bad response from server");
  }
  return response.json();
}).then((response) => {
  console.log('Discord Response', response);
}).catch((error) => {
  console.log(error);
});

标签: node.jsdiscordfetchdiscord.jshttp-status-code-400

解决方案


经过进一步研究,我发现以下视频对我有所帮助。

这是工作代码:

let options = {
  url: 'https://discord.com/api/oauth2/token',
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  body: new URLSearchParams({
    'client_id': discordInfo.client_id,
    'client_secret': discordInfo.client_secret,
    'grant_type': 'client_credentials',
    'code': req.query.code,
    'redirect_uri': discordInfo.callbackUrl,
    'scope': 'identify email'
  })
}

let discord_data = await fetch('https://discord.com/api/oauth2/token', options).then((response) => {
  return response.json();
}).then((response) => {
  return response;
});

推荐阅读