Reputation: 21
During the Oauth process for reddit API, I have gotten stuck at the access token request, getting an error saying 'unsupported_grant_type'. The API documentation says to use grant type 'authorization_code' which is what I have set now. I've tried using a string, URLSearchParams, and formData to correct it thinking that it was the format that was breaking it but nothing has worked.
Here is the function in question:
async function fetchAccessToken(){
console.log("fetching access token...");
const cred = btoa(`${client_id}:${client_secret}`);
var form = new FormData()
form.append('code', authCode)
form.append('grant_type', grantType)
form.append('redirect_uri', redirect_uri)
const response = await fetch('https://ssl.reddit.com/api/v1/access_token', {
method: 'POST',
headers: {
'Content-Type':"application/x-www-form-urlencoded",
'Authorization':`Basic ${cred}`
},
body: form
})
const data = await response.json();
console.log(response.status);//says 200
console.log(data);//says {error: 'unsupported_grant_type'}
}
I've been stuck here for over a week, any help would be appreciated.
Upvotes: 1
Views: 882
Reputation: 21
I was stuck on a similar issue - ended up using Axios. Make sure to add a unique 'User-Agent'.
const axios = require("axios").default;
const url = require("url");
async function fetchAccessToken(){
console.log("fetching access token...");
const client_id = "";
const client_secret = "";
const username = "":
const password = "";
const authData = {
grant_type: "password",
username: username,
password: password,
};
const params = new url.URLSearchParams(authData);
const response = await axios({
url: 'https://www.reddit.com/api/v1/access_token',
method: 'POST',
headers: {
'User-Agent': "myApp:V0.1 by Dschaar", //some unique user agent
},
auth: {
username: username,
password: password,
}
params: params
})
console.log(response.data);
}
Upvotes: 2