The status code is 500 and an Axios error occurred with a status code of 401. The error message states that headers cannot be set after they have already been sent to the client

In my Typescript code, I have implemented a function that retrieves the access_token and id_token by exchanging an Authorization code received after user authorization through 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);
    }
  }

Although this code was functioning correctly before, it has recently started displaying the error below:

>> 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 have tried researching this issue but cannot seem to pinpoint the problem. It was running smoothly a few days ago and now encounters an error.

I am expecting a response from the Google API containing the user's access, id, and refresh tokens.

Answer №1

Attempting to manually send a post request through PostMan resulted in an 'Unauthorized User' error response.

Upon further investigation, I discovered that I had previously created different Google OAuth client credentials for testing purposes and mistakenly used them as environment variables.

After correcting the Google OAuth client credentials (client_id, client_secret), the issue was resolved.

I am still puzzled by the misleading error message I received. If anyone has insight into why this occurred, please share your knowledge.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The type '(dispatch: Dispatch<any>, ownProps: OwnProps) => DispatchProps' does not match the parameter type 'DispatchProps'

Currently, I am working on a React application using Redux and TypeScript. I came across this insightful article that provided guidance on creating types for the mapStateToProps and mapDispatchToProps functions. Below is the code for my container: import ...

Find the combination of all potential function outputs

I'm trying to figure out why the compiler doesn't infer A as a union type like string[] | number[] when it fails. Instead, A is inferred as the first return value, which in this case is string[]. Is there a solution to this issue? const define = ...

Utilize mui-tiptap to effortlessly upload images to your content

My current project involves using the mui-tiptap module in React 18 with Vite. Specifically, I am facing an issue with uploading a local image to my backend. The problem seems to lie in my frontend code, as I am encountering a TypeScript error that is prev ...

Error encountered: 'applePaySession.completeMerchantValidation' is not a valid object reference when attempting to process a successful apple pay payment

So, I'm having an issue with the user's payment going through but encountering undefined value when checking compatibility. I've been trying to debug this problem in my code snippet below: setCanDisplayApplePay() { var client = n ...

What is the reason for importing this JS module in TypeScript with a "default" property?

This particular code snippet comes from a specialized i18n module, situated within ./esm/locale/en.js: import cardinal from '../rules/rule5'; import ordinal from '../rules/rule42'; var pluralRule = { ordinal: ordinal, cardinal: card ...

Real-time webpage updates with Spring Boot, Typescript, and IntelliJ

Working with Angular 2 using TypeScript and Spring Boot within Intellij. I have encountered an issue where changes made in my TypeScript file are not being reflected on the webpage, even though the generated JavaScript file shows the updates. Can anyone p ...

Fetching all data from a SQLite database in a Listview using React Native

I have been utilizing the library found at https://github.com/andpor/react-native-sqlite-storage in my react native project. To retrieve a single row from the database, I use the following code: db.transaction((tx) => { tx.executeSql('SEL ...

Tips on dynamically looping the formcontrolname and implementing validation strategies

Looking for a way to validate multiple looping of dynamic formControlName="xxx" in select field. Check out my HTML code: <ul *ngFor="let detaillist of stressli.stresstabdetails;"> <li> <div class="form-container"> ...

Fastify Schema Failing to Validate Incoming Requests

Currently, our backend setup involves using Node.js and the Fastify framework. We have implemented a schema in satisfy to validate user input. Below is the schema defined in schema.ts: export const profileSchema = { type: 'object', properti ...

Step-by-step guide on setting up pnpm directly, without the need to first

Here I am, faced with a brand new Windows 10 installation - only VS Code is installed and nothing more: Can pnpm be installed and used without the need for npm? Is this action beneficial or detrimental? Consideration: typescript ...

Tips for selecting specific regions on an Angular SVG map

For my Angular TypeScript project, I included a map. Does anyone know how to create a select region on the map? Click here for StackBlitz Here is the jsFiddle code link CSS styles here p { font-size: 12px; } #core { fill: #ff4f81; animatio ...

Having trouble resolving all parameters for the SiteNotificationComponent: (?)

I encountered an issue while attempting to append a component to the DOM. The error message displayed was "Can't resolve all parameters for SiteNotificationComponent: (?).at syntaxError." My goal was to insert HTML content by invoking showNotificatio ...

EventListener cannot be removed

My TypeScript class is structured like this: class MyClass { let canvas: any; constructor(canvas: any) { this.canvas = canvas; this.canvas.requestPointerLock = this.canvas.requestPointerLock; document.exitPointerLock = ...

Issues with displaying data tables in Vue using Axios and Laravel

My Vue.js users component utilizes jQuery datatables to display data, but upon running the code, I am seeing the data along with an unwanted message that reads "No data found". Can anyone provide assistance with this issue? As a newcomer to Frontend tools, ...

Serialization of objects is not possible in Angular JS post requests

At the moment, I am utilizing an AngularJS Post method to send data to my controller instead of a traditional form submission. The issue I am encountering is that after the post call, the object named sharingInfo in the controller always gets set to null. ...

Tips for embedding HTML/CSS snippets in backticks when using TypeScript with AngularJS

Does anyone else experience the issue of their Angular 2 templates showing up as gray text in Visual Studio Code? I'm unable to use autocomplete or see my CSS properly. Is this a settings problem or is there a plugin that can solve this? BTW, I am us ...

Can the 'this' keyword be used to declare the type in TypeScript in this manner?

For instance: // ===== Declaration ===== // class A { CONSTANTS_TYPE: { [key: string]: [any] } CONSTANTS: { [key in keyof this['CONSTANTS_TYPE']]: key } bar<T extends keyof this['CONSTANTS_TYPE'] | string>( type: T, ...

Issue with retrieving properties in Angular template due to undefined values in HTML

As a newbie to Angular, I am dedicated to improving my skills in the framework. In my project, I am utilizing three essential files: a service (Studentservice.ts) that emits an observable through the ShowBeerDetails method, and then I subscribe to this ob ...

Angular-template static functions refer to functions that do not require an

Our project utilizes the linting-config provided by AirBnB. There is a rule that stipulates class methods must utilize this or be declared as static. While this rule theoretically makes sense, it seems to present challenges within an angular context. Consi ...

Incorporating Jest alongside setTimeout and leveraging useFakeTimers

As I work with a TypeScript async function that requires a 1-second sleep between two statements, this implementation is in place: async function systemUnderTest(): Promise<void> { console.log("One"); await new Promise(r => { set ...