【发布时间】:2019-02-06 21:19:55
【问题描述】:
在使用 Passport.js、Express 和 Mongoose 时,我在 NodeJS 中遇到了这个奇怪的问题。基本上,即使我不发送多个标头,我也会收到一条错误消息“无法在标头发送到客户端后设置标头”。
我已经阅读了其他帖子并尝试了它们,但它们都没有奏效。
- 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 问题,但似乎找不到解决方案。我收到的问题是,当我发送多个响应标头时会触发此错误,但事实是我没有发送多个标头。看起来很奇怪。
这是我的堆栈跟踪:
(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 => {
if (!profile) {
return res.status(404).json({ error: "No Profile Found" });
}
else {
res.json(profile);
}
}).catch(err => {
console.log(err);
})
});
我了解错误的含义,但据我所知,我认为我不会发送多个标头,我什至通过 console.log 检查了仅运行了一个块。
提前非常感谢您! :)
完整代码:https://github.com/lourdesr/devlog
编辑:
我想通了。在尝试获取经过身份验证的用户时,这是我的 passport.js 中的一个问题。我忘记在导致它的“完成”方法上使用“返回”。刚刚添加了 return 语句,它就起作用了!
【问题讨论】:
-
您显示的服务器代码似乎不太可能导致有关发送标头的错误。必须有一些其他代码导致该错误。每当您尝试对同一请求发送多个响应时,就会出现该特定错误,并且通常是由不正确的异步代码引起的。
-
由于您从 jfriend00 的建议中找到了单独的解决方案,请发布您自己的问题答案并接受它。
标签: node.js express mongoose passport.js express-jwt