Im trying to make a login system with discord for my website that is made with express. I have made a function to get an access token so that I can use that function in the route.
Im trying to get an access token from: https://discord.com/api/oauth2/token
Here is my code:
async GetToken(code) {
let access_token;
const payload = {
'client_id': client_id,
'client_secret': client_secret,
'grant_type': 'authorization_code',
'code': code,
'redirect_uri': redirect_uri,
'scope': scope,
};
const config = {
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
};
fetch(discord_token_url, {
method: 'post',
body: payload,
headers: config.headers,
}).then(response => response.json()).then(json => console.log(json)).catch(err => console.log(err));
return access_token;
},
And here's the err I get:
{
error: 'unsupported_grant_type',
error_description: 'Grant type None is not supported'
}
As you can see I've given the correct grant type yet I get this error.
Forgot to update to add the solution and saw a lot of people looking at this so here's the solution (thanks to @Kira): You have to use URLSearchParams
// Modules
const fetch = require('node-fetch');
const { url } = require('inspector');
const { URLSearchParams } = require('url');
// Add the parameters
const params = new URLSearchParams();
params.append('client_id', client_id);
params.append('client_secret', client_secret);
params.append('grant_type', 'authorization_code');
params.append('code', code);
params.append('redirect_uri', redirect_uri);
params.append('scope', scope);
// Send the request
fetch('https://discord.com/api/oauth2/token', {
method: 'post',
body: params,
headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json' },
}).then(r => r.json()).then(Response => {
// Handle it...
handle()
});