carte blanche
carte blanche

Reputation: 11476

Error: Can't set headers after they are sent. in nodejs

I am running into the error show below on my app,line 413 points to “res.json(stat); // return in JSON format.” in below code, I looked at other posts with similar error but none helped me, why am I hitting this error ?appreciate any guidance on how to fix it?

app.post('/api/botjobs.json', function(req, res) {
    // console.log(req.body)
    data = req.body;
    var temp = {};
    temp.radar = data.radar;
    temp.request = data.request;
    if(temp.request == 'cloneradar'){
        temp['params.clonetype'] = data.params.clonetype;
    }
    now = new Date();
    data["updated"] = now;      
    // console.log('DATA:')
    // console.log(data)
    // console.log('TEMP:')
    // console.log(temp)
    botjobs.findOne(temp, {}, { sort:{'_id': -1}}, function(err, findstat){
        // console.log(findstat)
        // console.log(err)
        // console.log("inside botjobs findOne");
        if(findstat != null){
            // console.log('updating entry')
            //console.log(findstat);
            data['numupdated'] = findstat['numupdated']+1;
            // console.log(data);
            botjobs.update({'_id':findstat['_id']},data,{ upsert : true, multi: true },function(err,stat){
                if (err)
                    res.send(err);

                res.json(stat); // return in JSON format
            });

        }
        else{
            // console.log('creating new entry')
            data["created"] = now;
            data['numupdated'] = 0;
            botjobs.create(data,function(err, stat) {
                // console.log(stat);
                // if there is an error retrieving, send the error. nothing after res.send(err) will execute
                if (err)
                    res.send(err);

                res.json(stat); // return in JSON format. —> line 413 in route.js
            });
        }

    });

});

Error:-

Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:350:11)
    at ServerResponse.res.setHeader (/app/node_modules/express/node_modules/connect/lib/patch.js:134:22)
    at ServerResponse.res.set.res.header (/app/node_modules/express/lib/response.js:595:10)
    at ServerResponse.res.send (/app/node_modules/express/lib/response.js:151:12)
    at ServerResponse.res.json (/app/node_modules/express/lib/response.js:237:15)
    at /app/app/routes.js:413:10

Upvotes: 1

Views: 58

Answers (3)

Harshit Agarwal
Harshit Agarwal

Reputation: 2420

"Can't set headers after they are sent", this error occurs when u are trying to send something when the response is already sent. The res.send() ends the response so you cant send anything after res.send(). Why you are receiving this error is because the update call might be returning error and hence the res.send() is getting called which is inside if block. To avoid the can't set headers error in your case, you need to wrap inside if-else block, like this:

if (err){
 res.send(err);
}else{
 res.json(stat);
}

This will resolve the cant set headers issue, but your code still might fail because i think your update method is failing.

Upvotes: 0

Dishonered
Dishonered

Reputation: 8841

You can add a condition like this

if (err)
{
 res.send(err);
}
else
{
 res.json(stat);
}

Upvotes: 1

Mahdi P.
Mahdi P.

Reputation: 307

try return res.send(err); in place of res.send(err); for each res.send()

Upvotes: 0

Related Questions