Skip to content
Advertisement

Cannot set headers after they are sent to the client bug with Express and node-postgres

I’m stuck with the issue of sending response back to the caller after retrieving something from Postgres database.

It appears that headers are automatically written after fetchUserDB is executed (regardless of its success).

This leads to the error ERR_HTTP_HEADERS_SENT when I try to return the response back using res.json() menthod.

These are the headers after fetchUsedDB is called (just before return statement). Checking res._headers you can see that finished is set to true after the call is made.

JavaScript

This is the route managing the endpoint in question:

JavaScript

The error I’m getting is:

Uncaught Error Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

Here is the fetchUserDB code:

JavaScript

I’m using Express and node-postgres.

Advertisement

Answer

So after 2 days of struggling I found the solution. In one of my Express API middleware I did use next(). What solved the issue was to change it to return next()

This caused completely unexpected behaviour with axios and async/await.

When to use next() and return next() in Node.js

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement