我试图在我的代码中找到一个错误,其他主题都没有 .
有app.js代码,其中包含Express模块的 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
这段代码:
exports.all = function (cb) {
db.get().collection('notes').find().toArray(function (err, docs) {
cb(err,docs);
})
};
应用程序崩溃时出现此错误:
process.nextTick(function(){throw err;});
^
错误:发送后无法设置标头 . ServerResponse.jader上的ServerResponse.OutgoingMessage.setHeader(_http_outgoing.js:357:11)处于ServerResponse.jader(O:\ OGPI6 \ node_modules \ express \ lib \ response.js:725:10)处(O:\ OGPI6 \ node_modules) \ express \ lib \ response.js:253:10)位于O:\ OGPI6 \ controllers \ notes.js的ServerResponse.send(O:\ OGPI6 \ node_modules \ express \ lib \ response.js:158:21):9 :13: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)
在我看来,回调函数中只有“controller”错误:
if(err){
console.log(err);
return res.sendStatus(500);
}
res.send(docs);
但我认为当发生错误时它必须终止函数并返回 sendStatus(500)
,但在控制台中记录错误后它会尝试返回 res.send(docs)
然后应用程序崩溃,因为它正在发送第二个 Headers . 它看起来很好,但不起作用 . 任何人都可以指出我失败了吗?
2 回答
使用中间件中的“next”参数来表达已知完成此中间件的目的,并且不再需要执行代码 .
返回后执行代码可能是由于异步性质 .
你也可以使用else块 .
将代码更改为