在我的 NestJs 项目中,我使用装饰器@Res() res并使用响应对象通过多种情况设置自定义响应标头状态。调用时,有时会记录: Error [ERR_HTTP_HEADERS_SENT]: Cannot remove headers after they are sent to the client
在查看了 Github 上的问题列表并在互联网上搜索后,我知道这与 Express 中间件和 NestJs 的内置过滤器有关。
因此,我在 Controller 方法的末尾删除.send()并添加,日志就会消失。 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
}
Run Code Online (Sandbox Code Playgroud)
我修复后的代码如下所示:
@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;
}
Run Code Online (Sandbox Code Playgroud)
我的问题:我必须 return;在方法的末尾添加吗?为什么使用.send() 有时 会导致错误但并非总是如此 …