node.js - 400 从 Discord API 请求 token 时出错

标签 node.js discord fetch discord.js http-status-code-400

我正在尝试使用 Discord 的 API 创建登录流程。根据文档,我假设使用回调 URL 返回的 code 进行另一个调用以接收访问 token 。我已按照说明 here 进行操作。但是,我在调用电话时不断收到 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);
});

最佳答案

经过进一步研究,我发现了以下内容video这帮助了我。

这是工作代码:

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;
});

关于node.js - 400 从 Discord API 请求 token 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65237821/

相关文章:

不存在关系时的 Hibernate JOIN FETCH

javascript - 使用来自 componentDidMount React 中的 fetch 的属性渲染组件

javascript - 如何防止 typescript 将动态导入转换为require()?

javascript - 快速获取根事件不起作用

python - 我收到 KeyError : '563690668808208423' when i'm trying to add exp to user

python - react 编辑,只编辑discord.py中最新的命令

node.js - 使用 Upstart 运行 nodejs 应用程序

javascript - 大型 Angular 应用程序的项目结构?

javascript - Discord.JS 角色创建事件

javascript - 拦截 fetch() 请求,将其搁置并在满足特定条件时恢复