【问题标题】:NestJS - Cannot set headers after they are sent to the clientNestJS - 将标头发送到客户端后无法设置标头
【发布时间】: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


    【解决方案1】:

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

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

    return res.status(result.statusCode).json(result.data);
    

    因为如果您错过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
    

    【讨论】:

    • 谢谢你的解释,但我不能投票:((我没有足够的声誉)
    • 好的,我很高兴看到它对你很满意
    猜你喜欢
    • 2022-01-14
    • 2022-11-30
    • 2021-06-18
    • 2021-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-30
    相关资源
    最近更新 更多