2

I'm trying to create a login process with Discord's API. Per the documentation I'm suppose to use the code returned on the callback URL to make another call to receive the access token. I've followed the instructions here. However, I keep receiving a 400 error when making the call.

Any help on what I need to correct?

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);
});
SReca
  • 643
  • 3
  • 13
  • 37

1 Answers1

2

After further research, I discovered the following video which helped me out.

Here is the working code:

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;
});
SReca
  • 643
  • 3
  • 13
  • 37