NestJS - 发送到客户端后无法设置标头

vot*_*4it 6 node.js http-status express nestjs

在我的 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() 有时 会导致错误但并非总是如此

小智 16

因为requet.json({...})已经向“客户端”发送了响应。因此.send()之后requet.json({...})将尝试发送另一个响应。

最好的方法是返回这样的响应:

return res.status(result.statusCode).json(result.data);
Run Code Online (Sandbox Code Playgroud)

因为如果你错过了return你的代码可能会导致意想不到的结果。

例子:

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
Run Code Online (Sandbox Code Playgroud)