I have written this code in typescript which fetches access_token
and id_token
in exchange with the Authorization code which I recieve after user's authorization from Google OAuth.
public async getGoogleOAuthTokens({ code }: { code: string }): Promise<GoogleTokensResult> {
const rootURL = 'https://oauth2.googleapis.com/token';
const values = {
code,
client_id: GOOGLE_AUTH_CLIENT_ID,
client_secret: GOOGLE_AUTH_CLIENT_SECRET,
redirect_uri: GOOGLE_AUTH_REDIRECT_URL,
grant_type: 'authorization_code',
};
const authTokenURL = `${rootURL}?${qs.stringify(values)}`;
try {
const res = await axios.post<GoogleTokensResult>(authTokenURL, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
});
return res.data;
} catch (error: any) {
console.log(error.message);
throw new Error(error);
}
}
The code was working fine until suddenly it started giving the following error:
>> StatusCode:: 500, Message:: AxiosError: Request failed with status code 401
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at new NodeError (node:internal/errors:399:5)
at ServerResponse.setHeader (node:_http_outgoing:645:11)
at ServerResponse.header (D:\backend\node_modules\express\lib\response.js:794:10)
at ServerResponse.send (D:\backend\node_modules\express\lib\response.js:174:12)
at ServerResponse.json (D:\backend\node_modules\express\lib\response.js:278:15)
at errorMiddleware (D:\backend\src\middlewares\error.middleware.ts:11:24)
at Layer.handle_error (D:\backend\node_modules\express\lib\router\layer.js:71:5)
at trim_prefix (D:\backend\node_modules\express\lib\router\index.js:326:13)
at D:\backend\node_modules\express\lib\router\index.js:286:9 at Function.process_params
I tried researching on this issue I don't understand the problem. I don't understand the issue with this as it was working just fine couple of days ago and now it throws error.
I expect a response from the Google Api containing the access, id and refresh token of the user.
I tried to manually send post request through PostMan, the error response was 'Unauthorized User'.
Then I realized that, a while back, I created another Google Oauth Client credentials for testing and changed the environment variables with them.
So, I corrected the Google Oauth Client credentials (client_id, client_secret) and the problem solved.
I am still confused about the error message I got since it showed a completely different thing. If someone knows why did this happen, do let me know.