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

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

问题描述

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

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.

  • app.get - is there any difference between res.send vs return res.send
  • Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
  • Cannot set headers after they are sent to the client

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

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.

这是我的堆栈跟踪:

(节点:9236)DeprecationWarning:不建议使用当前URL字符串解析器,并将在以后的版本中将其删除.要使用新的解析器,请将选项{useNewUrlParser:true}传递给MongoClient.connect.

(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.

服务器在端口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)
  在< anonymous>

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>

这是我的服务器代码:

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);
  })
});

我了解错误的含义,但据我所知,我认为我没有发送多个标头,甚至通过console.log检查是否仅运行了一个块.

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.

非常感谢您! :)

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

我知道了.尝试获取经过身份验证的用户时,这是我的password.js文件中的问题.我忘了在造成这种情况的完成"方法上使用返回".刚刚添加了return语句就可以了!

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.

在这里:

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

您需要将其更改为:

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

您不希望代码在完成res.status(404).json({ errors });之后继续执行,因为它随后将尝试发送另一个响应.

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.

此外,到处都是:

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;
}

抛出到异步回调中的代码只是返回到node.js事件系统中,并没有抛出到您可以实际捕获的任何地方.此外,它不会发送对http请求的响应.换句话说,它实际上并没有执行服务器应该执行的操作.因此,请帮自己一个忙,不要在服务器中编写该代码.遇到错误时,请发送错误响应.

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.

由于您似乎是这里的新手,因此我想在 https://github.com/lourdesr/devlog ,因为只有这样我才能看到发生错误的地方.

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天全站免登陆