我是Node的新手。我试图绕过这个错误,我不明白为什么。我看过它的几个帖子,但它们都是不同的情况,没有一个与我相匹配。所以感谢帮助。从我在其他帖子中看到的情况来看,这是一个帖子中的大多数情况,我的确是一个得到的错误。
GET /posts/56f2a808653270ff11f7ddb2 304 30.391 ms - -
_http_outgoing.js:344
throw new Error('Can\'t set headers after they are sent.');
^
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:344:11)
at ServerResponse.header (/Users/me/nodyhead/node_modules/express/lib/response.js:718:10)
at ServerResponse.json (/Users/me/nodyhead/node_modules/express/lib/response.js:246:10)
at /Users/me/nodyhead/routes/index.js:50:13
at next (/Users/me/nodyhead/node_modules/mongoose/lib/model.js:2491:5)
at EventEmitter.<anonymous> (/Users/me/nodyhead/node_modules/mongoose/lib/model.js:2621:5)
at EventEmitter.<anonymous> (/Users/me/nodyhead/node_modules/mpromise/lib/promise.js:180:45)
at emitThree (events.js:97:13)
at EventEmitter.emit (events.js:175:7)
at Promise.safeEmit (/Users/me/nodyhead/node_modules/mpromise/lib/promise.js:83:21)
at Promise.fulfill (/Users/me/nodyhead/node_modules/mpromise/lib/promise.js:104:24)
at Promise.resolve (/Users/me/nodyhead/node_modules/mongoose/lib/promise.js:142:23)
at next (/Users/me/nodyhead/node_modules/mongoose/lib/model.js:2687:15)
at /Users/me/nodyhead/node_modules/kareem/index.js:177:19
at /Users/me/nodyhead/node_modules/kareem/index.js:109:16
at nextTickCallbackWith0Args (node.js:420:9) [nodemon] app crashed - waiting for file changes before starting...
这是我抱怨的三个功能
router.get('/posts', function(req, res, next) {
Post.find(function(err, posts) {
if (err) { return next(err); }
res.json(posts);
});
});
router.param('post', function(req, res, next, id) {
var query = Post.findById(id);
query.exec(function(err, post) {
if (err) { return next(err); }
if (!post) { return next(new Error('can\'t find post')); }
req.post = post;
return next();
});
});
router.get('/posts/:post', function(req, res) {
req.post.populate('comments', function(err, post) {
if (err) { return next(err); }
res.json(post);
});
res.json(req.post);
});
答案 0 :(得分:0)
嗯,问题是你两次调用res.json()。有关详细信息,请参阅本主题Error: Can't set headers after they are sent to the client的答案
答案 1 :(得分:0)
在GET posts/:post
(您的上一个处理程序)中删除其中一条res.json(obj)
行。这里的要点是你的响应是两次:一次是在回调执行之前,一次是在数据库访问之后。只保留其中一个。