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

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


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

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

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

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

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

Whole code:

Problem courtesy of: tomekfranek


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


Leave a Reply

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