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?