My server crashed and I found the following error in my logs:
Error: Can't set headers after they are sent.
and I could not reproduce the error. I think I found a fix, but I want to ensure that I understand the problem, which is outlined in the code below. Based on this post, I believe it is coming from the multiple res.send(..)
calls in my Express router:
router.post('/adduser', function(req, res) {
var msg = '(message okay)'
var db = req.db;
db.collection('userlist').find({
username: req.body.username;
}).toArray(function(err, items) {
// verify the user, set session fields, etc...
console.log("message after user verification is: ");
console.log(msg);
res.send({
msg: msg
});
});
// Insert the request's data into the 'userlist' collection.
db.collection('userlist').insert(body, function(err, result) {
console.log("inserting into userlist...");
res.send(
(err === null) ? {
msg: msg
} : {
msg: err
}
);
});
console.log("message after user verification is: ");
console.log(msg);
}
The last few lines of my log are:
message after user verification is:
(message okay)
POST /login/adduser 200 7ms - 10b
inserting into userlist...
/home/lucas/mynode/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/c
onnection/base.js:245
throw message;
^
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (http.js:689:11)
at ServerResponse.header (/home/lucas/mynode/node_modules/express/lib/response.js:717:10)
at ServerResponse.send
I suspect that I am calling the res.send(..)
twice, so I believe that I fixed this by removing the first res.send(..)
, but is this the correct fix? Also, if calling res.send(..)
twice causes the error, then why can't I reproduce this bug? I never got the error, but another user did.
Can anyone provide an explanation? Feedback on my solution would also be very helpful.