[ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

痛定思痛。 2023-10-12 19:38 143阅读 0赞

问题描述

如果你的node.js提示:[ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

那么,代表你返回了结果,但是最后你又不小心再返回了一次。通常是由于方法没有进行等待,或者多条件判断缺漏造成的。


解决方案:

情况一:返回机制问题

通过success/error模式来返回结果,取消最终的默认返回;

或者通过await方法返回再return结果即可。

  1. axios.get(optionsEntitlement.url,{headers,httpsAgent})
  2. // axios.get(optionsEntitlement.url,optionsEntitlement)
  3. .then(function (response) {
  4. // handle success
  5. console.log("entitlement success:"+response);
  6. res.status(200).send(response)
  7. }).catch(function (error) {
  8. // handle error
  9. console.log("entitlement error:"+error);
  10. res.status(500).send({
  11. "message": {
  12. "code": "AIE0001",
  13. "type": "E",
  14. "timestamp": new Date().toISOString(),
  15. "text": "System Unavailable",
  16. error
  17. }
  18. });
  19. });
  20. // res.json({ title: 'LMD GCS Node - entitlement' });
  21. });

情况二:

服务器会输出响应头,再输出主体内容,如果你在代码中设置了res.writeHead()函数,然后再使用res.send()方法,就会出现这个错误。通常要使用res.end()

  1. const body = 'hello https://zhengkai.blog.csdn.net/';
  2. response
  3. .writeHead(200, {
  4. 'Content-Length': Buffer.byteLength(body),
  5. 'Content-Type': 'text/json;charset=utf-8',
  6. })
  7. .end(body);

认识 Express 的 res.send() 和 res.end()

#

相同点

Express 的 res.end() 和 res.send() 方法的相同点:

  1. 二者最终都是回归到 http.ServerResponse.Useresponse.end() 方法。
  2. 二者都会结束当前响应流程。

不同点

Express 的 res.end() 和 res.send() 方法的不同点:

  1. 前者只能发送 string 或者 Buffer 类型,后者可以发送任何类型数据。
  2. 从语义来看,前者更适合没有任何响应数据的场景,而后者更适合于存在响应数据的场景。

总结

Express 的 res.end() 和 res.send() 方法使用上,一般建议使用 res.send()方法即可,这样就不需要关心响应数据的格式,因为 Express 内部对数据进行了处理。

发表评论

表情:
评论列表 (有 0 条评论,143人围观)

还没有评论,来说两句吧...

相关阅读