我试图在我的代码中查找错误,而其他主题没有任何结果。发送后无法设置标题
有app.js代码,其包含来自快车模块get
方法:
app.get('/notes', notesController.all);
有notesController.js代码,其中出口到app.js create
方法:
exports.all = function (req, res) {
Notes.all(function(err, docs){
if(err){
console.log(err);
return res.sendStatus(500);
}
res.send(docs);
})
};
在model
此编码:
应用程序崩溃与这个错误:
process.nextTick(function() { throw err; }); ^
Error: Can't set headers after they are sent. at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:357:11) at ServerResponse.header (O:\OGPI6\node_modules\express\lib\response.js:725:10) at ServerResponse.json (O:\OGPI6\node_modules\express\lib\response.js:253:10) at ServerResponse.send (O:\OGPI6\node_modules\express\lib\response.js:158:21) at O:\OGPI6\controllers\notes.js:9:13 at O:\OGPI6\models\notes.js:6:9 at handleCallback (O:\OGPI6\node_modules\mongodb\lib\utils.js:120:56) at O:\OGPI6\node_modules\mongodb\lib\cursor.js:860:16 at handleCallback (O:\OGPI6\node_modules\mongodb-core\lib\cursor.js:171:5) at setCursorDeadAndNotified (O:\OGPI6\node_modules\mongodb-core\lib\cursor.js:505:3)
在我的脑海里唯一的错误,在回调函数“控制器”:
if(err){
console.log(err);
return res.sendStatus(500);
}
res.send(docs);
但我认为,当发生错误,必须终止函数并返回sendStatus(500)
,但登录后它尝试返回的控制台中的错误res.send(docs)
,然后应用程序崩溃,因为它正在发送第二个标头。它看起来很好,但没有工作。任何人都可以指出我失败的方式吗?
您是否认为''exports.all'方法可能会多次触发回调。你有没有试图在回调开始时放置一个'console.log'? –
我同意@BenjiLees,它看起来像回调被召唤两次。 – robertklep