【发布时间】:2021-09-06 20:28:52
【问题描述】:
在我的 NestJs 项目中,我使用装饰器 @Res() res 并使用响应对象来设置自定义响应头状态。
调用时,有时会记录: Error [ERR_HTTP_HEADERS_SENT]: Cannot remove headers after they are sent to the client
我在 Github 中查看问题列表并在互联网上搜索后,我知道这与 Express 中间件和 NestJs 的内置过滤器有关。
所以,我把.send()去掉,在Controller方法的最后加上 return;,日志就消失了。
我的第一个代码:
@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
}
我修复后的代码如下所示:
@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;
}
我的问题:我必须在方法末尾添加 return; 吗?为什么使用.send()有时会导致错误,但不会总是?
【问题讨论】:
标签: node.js express nestjs http-status