Res.send () - Unable to set headers after sending them
I am creating an API with Node js and I have a problem with multiple api parameters. I am getting multiple docs from couchbase. The API returns multiple JSON documents, but after that the program crashes. I res.send()
only call once. I don't understand where I am going wrong. This is my API:
router.get("/employee/collectinsert/:_startdate/:_enddate", function(req, res, next){
var startDate = moment(req.params._startdate);
var endDate = moment(req.params._enddate);
var daysOfYear = [];
for(var date = moment(startDate); date.diff(endDate,'days') < 1; date.add(1, 'days')){
daysOfYear.push(formatDate(date));
}
bucket.getMulti(daysOfYear,function(err, results){
if(err) throw err;
for(var key in results) {
if(results.hasOwnProperty(key)) {
if(results[key].error) {
console.log("`" + key + "`: " + JSON.stringify(results[key]));
}
res.send(results);
}
}
process.exit(0);
});
});
And I am getting this error:
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:357:11)
at ServerResponse.header (C:\Users\ekaplan\Desktop\dashboard\node_modules\express\lib\response.js:730:10)
at ServerResponse.send (C:\Users\ekaplan\Desktop\dashboard\node_modules\express\lib\response.js:170:12)
at C:\Users\ekaplan\Desktop\dashboard\api\employee.js:53:21
at C:\Users\ekaplan\Desktop\dashboard\node_modules\couchbase\lib\bucket.js:1280:9
+3
source to share
3 answers
You call res.send () multiple times as it is in a for loop.
Move it outside of the loop:
bucket.getMulti(daysOfYear,function(err, results){
if(err) throw err;
for(var key in results) {
if(results.hasOwnProperty(key)) {
if(results[key].error) {
console.log("`" + key + "`: " + JSON.stringify(results[key]));
}
}
}
res.send(results); // called once when for loop has finished
});
+4
source to share
yours res.send
is in a loop and you can only send one response.
You might want to do this:
bucket.getMulti(daysOfYear,function(err, results){
if(err) throw err;
for(var key in results) {
if(results.hasOwnProperty(key)) {
if(results[key].error) {
console.log("`" + key + "`: " + JSON.stringify(results[key]));
}
}
}
res.send(results);
}
+1
source to share