簡體   English   中英

node.js如何使用json對象數組發送響應?

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

我想使用node.js的pivotal-node模塊返回完成的關鍵故事數組。

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.
  });
});

我做錯了什么? 以及如何解決它? 我收到一個錯誤:

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

整個代碼: https//gist.github.com/regedarek/30b2f35e92a7f98f4e20

pivotal.getStories()異步的

它的回調(因此response.send() )將在其余代碼(包括response.end()之后運行一段時間

實際上,你根本不應該調用response.end() ; response.send()為你做到了。

你也不能多次調用response.send() ; 你需要將所有結果組合成一個數組並發送它。
這並不簡單; 考慮使用async.js或promises。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM