ERR_HTTP_HEADERS_SENT:发送到客户端后无法设置头 [英] ERR_HTTP_HEADERS_SENT: Cannot set headers after they are sent to the client

查看:44
本文介绍了ERR_HTTP_HEADERS_SENT:发送到客户端后无法设置头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

与 Passport.js、Express 和 Mongoose 一起使用时,我在 NodeJS 中遇到了这个奇怪的问题.基本上,即使我不发送多个标头,我也会收到一条错误消息,指出在将标头发送到客户端后无法设置标头".

我读过其他帖子并尝试过,但都没有奏效.

我已经挖掘了 github 问题,但似乎找不到解决方案.我收到的问题是,当我发送多个响应标头时会触发此错误,但事实是我没有发送多个标头.看起来很奇怪.

这是我的堆栈跟踪:

<块引用>

(node:9236) DeprecationWarning:当前 URL 字符串解析器已被弃用,并将在未来版本中删除.要使用新的解析器,请将选项 { useNewUrlParser: true } 传递给 MongoClient.connect.

在端口 5000 上运行的服务器
MongoDB 连接错误
[ERR_HTTP_HEADERS_SENT]:发送到服务器后无法设置标头客户
  在validateHeader (_http_outgoing.js:503:11)
  在 ServerResponse.setHeader (_http_outgoing.js:510:3)
  在 ServerResponse.header (/Users/lourdesroashan/code/github/devlog/node_modules/express/lib/response.js:767:10)
  在 ServerResponse.json (/Users/lourdesroashan/code/github/devlog/node_modules/express/lib/response.js:264:10)
  在 Profile.findOne.then.profile (/Users/lourdesroashan/code/github/devlog/routes/api/profile.js:27:30)
  在 <匿名>

这是我的服务器代码:

router.get("/userprofile",passport.authenticate('jwt', { session: false }), (req, res) => {Profile.findOne({ user: req.user.id }).then(profile => {如果(!个人资料){返回 res.status(404).json({ error: "No Profile Found" });}别的 {res.json(配置文件);}}).catch(err => {控制台日志(错误);})});

我明白错误意味着什么,但据我所知,我认为我没有发送多个标头,我什至通过 console.log 检查了只有一个块在运行.

先谢谢你!:)

完整代码位于:https://github.com/lourdesr/devlog

我想通了.在尝试获取经过身份验证的用户时,这是我的passport.js 中的一个问题.我忘记在导致它的完成"方法上使用返回".刚刚添加了 return 语句,它起作用了!

解决方案

每当您尝试向同一个请求发送多个响应时,就会发生该特定错误,并且通常是由不正确的异步代码引起的.

您在问题中显示的代码似乎不会导致该错误,但我确实在不同的路径中看到了代码 此处 会导致该错误.

你在哪里:

if (!user) {errors.email = "未找到用户";res.status(404).json({错误});}

您需要将其更改为:

if (!user) {errors.email = "未找到用户";res.status(404).json({错误});//在此回调中停止进一步执行返回;}

您不希望代码在完成后继续运行 res.status(404).json({ errors }); 因为它随后会尝试发送另一个响应.><小时>

此外,您随处可见:

if (err) throw err;

在异步回调中,您需要将其替换为实际发送错误响应的内容,例如:

if (err) {控制台日志(错误);res.sendStatus(500);返回;}

在异步回调中抛出只会返回到 node.js 事件系统中,而不会被抛出到您可以实际捕获它的任何地方.此外,它不会发送对 http 请求的响应.换句话说,它并没有真正做服务器应该做的事情.所以,帮自己一个忙,永远不要在你的服务器上写那些代码.收到错误时,发送错误响应.

<小时>

因为看起来您可能是新来的,我想称赞您在 https://github.com/lourdesr/devlog 因为只有通过查看我才能看到发生错误的地方.

I'm facing this weird issue in NodeJS when using with Passport.js, Express and Mongoose. Basically, I get an error saying "Cannot set headers after they are sent to the client" even though I don't send more than one header.

I've read other posts and tried them out as well, and none of them worked.

I've dug through github issues and I can't seem to find a solution. I get the problem that this error is triggered when I send multiple response headers, but the fact is that I am not sending multiple headers. It seems just weird.

This is my stack trace:

(node:9236) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.

Server Running on port 5000
MongoDB Connected Error
[ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
  at validateHeader (_http_outgoing.js:503:11)
   at ServerResponse.setHeader (_http_outgoing.js:510:3)
   at ServerResponse.header (/Users/lourdesroashan/code/github/devlog/node_modules/express/lib/response.js:767:10)
   at ServerResponse.json (/Users/lourdesroashan/code/github/devlog/node_modules/express/lib/response.js:264:10)
   at Profile.findOne.then.profile (/Users/lourdesroashan/code/github/devlog/routes/api/profile.js:27:30)
   at <anonymous>

This is my server code:

router.get("/userprofile", passport.authenticate('jwt', { session: false }), (req, res) => {

  Profile.findOne({ user: req.user.id }).then(profile => {
    if (!profile) {
      return res.status(404).json({ error: "No Profile Found" });
    }
    else {
      res.json(profile);
    }
  }).catch(err => {
    console.log(err);
  })
});

I understand what the error means, but from what I know, I don't think I am sending multiple headers, I even checked by console.log that only one of the blocks is run.

Thank you so much in advance! :)

Full Code at: https://github.com/lourdesr/devlog

EDIT:

I figured it out. It was a problem in my passport.js while trying to get the authenticated user. I forgot to use 'return' on the 'done' method, which had caused it. Just added the return statement and it worked!

解决方案

That particular error occurs whenever you try to send more than one response to the same request and is usually caused by improper asynchronous code.

The code you show in your question does not appear like it would cause that error, but I do see code in a different route here that would cause that error.

Where you have this:

if (!user) {
  errors.email = "User not found";
  res.status(404).json({ errors });
}

You need to change it to:

if (!user) {
  errors.email = "User not found";
  res.status(404).json({ errors });
  // stop further execution in this callback
  return;
}

You don't want the code to continue after you've done res.status(404).json({ errors }); because it will then try to send another response.


In addition, everywhere you have this:

if (err) throw err;

inside an async callback, you need to replace that with something that actually sends an error response such as:

if (err) {
    console.log(err);
    res.sendStatus(500);
    return;
}

throwing inside an async callback just goes back into the node.js event system and isn't thrown to anywhere that you can actually catch it. Further, it doesn't send a response to the http request. In otherwords, it doesn't really do what the server is supposed to do. So, do yourself a favor and never write that code in your server. When you get an error, send an error response.


Since it looks like you may be new here, I wanted to compliment you on including a link to your full source code at https://github.com/lourdesr/devlog because it's only by looking at that that I was able to see this place where the error is occuring.

这篇关于ERR_HTTP_HEADERS_SENT:发送到客户端后无法设置头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆