I`m trying to find an error in my code, and nothing from other topics fits.
There is app.js code, which contains get
method from Express module:
app.get('/notes', notesController.all);
There is notesController.js code, which exports to app.js create
method:
exports.all = function (req, res) {
Notes.all(function(err, docs){
if(err){
console.log(err);
return res.sendStatus(500);
}
res.send(docs);
})
};
In model
this code:
exports.all = function (cb) {
db.get().collection('notes').find().toArray(function (err, docs) {
cb(err,docs);
})
};
App crashes with this error:
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)
At my mind only error with "controller" in the callback function:
if(err){
console.log(err);
return res.sendStatus(500);
}
res.send(docs);
But I thought that when an error occurs it must terminate function and return sendStatus(500)
, but after logging an error in the console it tries to return res.send(docs)
and then the app crashes because it is sending the second header. It looks fine but doesn`t work. Can anyone point which way I have failed?
exports.all
method might be firing off the call back multiple times. Have you tried to put aconsole.log
at the beginning of the callback? – Benji Lees