How in node.js send response with array of json objects?

How in node.js send response with array of json objects?

Problem

I want to return array of finished pivotal stories using pivotal-node module for node.js.

app.get('/delivered_stories', function(request, response) {             
  pivotal.useToken("my_token");
  pivotal.getProjects(function (err, data) {
    var project_ids = data.project.map(function(x) { return parseInt(x.id); });
    console.log('Retrived project ids: '.blue + project_ids);

    project_ids.forEach(function(id) {
      pivotal.getStories(id, { filter: "state:finished" }, function(err, story) {
        response.send(story);
      });
    });
    response.end(); // End the JSON array and response.
  });
});

What I am doing wrong? And how to fix it? I get an error:

http.js:708
    throw new Error('Can\'t set headers after they are sent.');
          ^
Error: Can't set headers after they are sent.

Whole code: https://gist.github.com/regedarek/30b2f35e92a7f98f4e20

Problem courtesy of: tomekfranek

Solution

pivotal.getStories() is asynchronous.

Its callback (and therefore response.send()) will run some time after the rest of your code (including response.end())

In fact, you shouldn’t be calling response.end() at all; response.send() does that for you.

You also cannot call response.send() more than once; you need to combine all of the results into a single array and send that.
This is not simple to do; consider using async.js or promises.

Solution courtesy of: SLaks

Discussion

Leave a Reply

Your email address will not be published. Required fields are marked *