Amir Gilboa Amir Gilboa - 6 months ago 9
Node.js Question

Nodejs: Can't set headers after they are sent

This node/express function is giving me an error:
Can't set headers after they are sent.
it used to work fine, but i have made some changes to the user schema, moving all address items to be under 'address', like this:



firstname,
lastname,
address:{
street,
city,
loc (array of numbers)
...
}





so the new function looks like this:



export function searchMembers(req, res) {
var lat = req.body.lat;
var lon = req.body.lon;
var zoom = req.body.zoom || 14;

var query = User.find();
var distance = 5000;

// when this line is removed, problem is gone:
query = query.where('address.loc').near({center:{type:'Point', coordinates:[lon,lat]}, maxDistance: distance, spherical:true});
query = query.where({'address.city': 'Toronto'});
query = query.sort({'lastname': 1});

query.exec(function(err,users){
if(err) res.send(err);

var final = [];
_.forEach(users, function(x){
var obj = {};
obj.id = x._id;
obj.name=x.firstname + ' ' + x.lastname;
obj.latitude=x.address.loc[1] ;
obj.longitude=x.address.loc[0] ;

final.push(obj);
});
res.status(200).json(final);
});
}





So when i run this, i get the funny error: Can't set headers after they are sent.
pointing to the last line in the function:
res.status(200).json(final);

i tried to eliminate stuff to find the root cause.
when i remove the where line with the 'near' function, the problem is gone.
i have added other filtering, just for testing, everything fine. only this one is causing an issue.
Any idea?

Answer

This error means, that you already used method res.json()/render()/send() and you try to do it again.

In your case, this line does not stop method from executing if(err) res.send(err);

You have to write return to stop it.

if(err) {
    res.send(err);
    return;
}

Which is equivalent to

if(err) {
    return res.send(err);
}

Just do not think about it as returning "res.send(err)", it is using res.send(err) and after that using return to stop executing.


The reason why removing line also removes error :

You have some error in that line (like having bad column names), therefore in callback the error is send and then you use res.send(err) and after that you call res.status(200).json(final)

Comments