emre kaplan
emre kaplan

Reputation: 198

res.send() - Can't set headers after they are sent

I'm creating API with Node js, and I have a problem with multiple parameters api. I'm getting multiple documents from couchbase. The API returns the multiple JSON documents, but after that, the program crashes. I call res.send() only one time. I don't understand where I'm 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'm 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

Upvotes: 3

Views: 6123

Answers (3)

Stretch0
Stretch0

Reputation: 9251

You are calling 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
});

Upvotes: 4

mJehanno
mJehanno

Reputation: 866

your res.send is in a loop, and you can only send one response.

You probably 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);
}

Upvotes: 1

Grynets
Grynets

Reputation: 2525

Because first you have to set headers like this res.header("Access-Control-Allow-Origin", "*"); and than make one send, as @Stretch0 said.

Upvotes: 0

Related Questions