I am using the GitHub API to authenticate a user, and get an authentication code. Now, however, I have to exchange this authentication code for an access token from the user’s github account.
I’ve followed the documentation, but it’s not working. I am getting different errors depending on what I try.
const tokenUrl = 'https://github.com/login/oauth/access_token';
const headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json'
};
const params = new URLSearchParams();
params.append('client_id', clientId);
params.append('client_secret', clientSecret);
params.append('redirect_uri', redirectUri);
params.append('code', code);
try {
const response = await fetch(tokenUrl, {
method: 'POST',
headers: headers,
body: params,
mode: 'no-cors'
});
if (response.ok) {
const parsedResponse = await response.json();
if (parsedResponse) {
const accessToken = parsedResponse.access_token;
console.log('personal access token', accessToken);
// Use the access token to make API requests on behalf of the user
} else {
console.error('Failed to parse response');
}
} else {
console.error('Failed to fetch token:', response.status, response.statusText);
}
} catch (error) {
console.error('Error fetching token:', error);
}
This gives me this error: Failed to fetch token: 0
When I try this:
const GITHUB_HEADERS = { 'Authorization': 'Bearer ghp_...' };
const GITHUB_BODY = {
"client_id" : clientId,
"client_secret" : clientSecret,
"redirect_uri" : redirectUri,
"code" : code
};
const response = await fetch(tokenUrl, {
method: 'POST',
headers: GITHUB_HEADERS,
body: JSON.stringify(GITHUB_BODY),
mode: 'no-cors'
})
if(response) {
const parsedResponse = response.json()
console.log('response successful', response.json())
if(parsedResponse) {
//const accessToken = parsedResponse.access_token;
}
}
I get this error:
POST https://github.com/login/oauth/access_token net::ERR_ABORTED 404 (Not Found)
response successful Promise {<rejected>: SyntaxError: Unexpected end of input
at TemplatesPreview.getUserToken (http://localhost:6262/di…}
Uncaught (in promise) SyntaxError: Unexpected end of input (at templates-preview.tsx:145:1)
at TemplatesPreview.getUserToken (templates-preview.tsx:145:1)
Any ideas?