Amir Gilboa Amir Gilboa - 1 year ago 58
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:

loc (array of numbers)

so the new function looks like this:

export function searchMembers(req, res) {
var 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({'': 'Toronto'});
query = query.sort({'lastname': 1});

if(err) res.send(err);

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


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:

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 Source

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) {

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)