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

1

7

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?

Touslesmois answered 6/9, 2021 at 12:17 Comment(0)
L
16

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
Lashonda answered 6/9, 2021 at 12:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.