0

I'm still very new to node.js,the array over here consists a list of ids. When I'm sending the response from the forEach loop, I'm getting Error: Can't set headers after they are sent. I googled it but could not understand properly

array.forEach(function(data) {
            db.collection.find({
                _id: mongoskin.helper.toObjectID(data)
            }).toArray(function(err, data1) {
                if (err) return next(err);
                console.log(data1);
                res.send(data1);
            })
        })
learner
  • 143
  • 2
  • 3
  • 11
  • check out this http://stackoverflow.com/questions/7042340/node-js-error-cant-set-headers-after-they-are-sent – vineet May 16 '16 at 05:00

3 Answers3

3

Because of the loop, your code is calling res.send multiple times; you can't do that

res.send is an overloaded function that can be called in multiple ways, but any way you use it, it will set headers and send a response. Think of it like an all-in-one, tries-to-be-the-smart-one function.

// not actual source code!
// just imagine res.send kinda like this
function send(body, headers, status) {
  res.setHeaders(headers);
  res.statusCode = status;
  res.write(body);
  res.end();
}

However, if you want to write a response piecewise, use the res.write method instead. When you're done, you must call res.end.

res.setHeader(myHeaders);
myArray.forEach(
  //...
  res.write(something);
);
res.end();
Mulan
  • 129,518
  • 31
  • 228
  • 259
0

This happens when res.end() is called more then once. The res.send() method is an easy way to respond without need to specify the type of data you are sending BUT it can be called only once. see express docs

This is how the res.send() method ends - express source

  // respond
  this.end(head ? null : body);
  return this; 
Yaki Klein
  • 3,978
  • 3
  • 37
  • 34
0

use this code,

var index = 0;
var object = [] // empty array
function find(){
    if(array.length -1 >=index){
        var data = array[index] ;
            db.collection.find({
                _id: mongoskin.helper.toObjectID(data)
            }).toArray(function(err, data1) {
                if (err) return next(err);
                console.log(data1);
            object.push(data1);
                //res.send(data1);
             index++;
             find();
            })

    }else{
         res.send(object);
    }
}

In your case ,you are sending response data but your array is still processing .so once your response sent ,you cant send it again .

Manoj Ojha
  • 373
  • 2
  • 11