vothanhliem1994it
vothanhliem1994it

Reputation: 83

NestJS - Cannot set headers after they are sent to the client

In my NestJs project, I am using decorator @Res() res and using the response object to set custom response header status by multiple cases. When calling, sometimes it logs: Error [ERR_HTTP_HEADERS_SENT]: Cannot remove headers after they are sent to the client

After I viewed the issues list in Github and searching on the internet, I know this is relating to Express middleware and the built-in filter of NestJs.

So, I remove .send() and add return; at the end of the Controller method, the log will disappear.

My first code:

@Get()
get(@Req() req, @Res() res) {
  const result = this.service.getData(req);
  res.status(result.statusCode).json(result.data).send(); // when using .send(), it will cause error
}

Code after I fixed look like this:

@Get()
get(@Req() req, @Res() res) {
  const result = this.service.getData(req);
  res.status(result.statusCode).json(result.data); // when remove .send(), it will succeed
  return;
}

My question: Do I have to add return; at the end of the method? Why using .send() sometimes cause error but not always?

Upvotes: 8

Views: 12703

Answers (1)

Georges Feungap
Georges Feungap

Reputation: 545

because requet.json({...}) already send response to "client". So .send() after requet.json({...}) will try to send another response.

the good way to do is to return response like this:

return res.status(result.statusCode).json(result.data);

because if you miss return your code may cause unexpected result.

Example:

res.status(result.statusCode).json(result.data); //response is sent
let a = "Something good"; // Code will be executed
console.log(a); // Code will be executed

Upvotes: 16

Related Questions