【问题标题】:How to generate multiple response.write:s with json in node.js/express?如何在 node.js/express 中使用 json 生成多个 response.write:s?
【发布时间】:2015-07-05 13:34:49
【问题描述】:

从 node.js 中的 api 调用生成多个 response.write:s 时遇到一些问题。这是代码。

 // get the articles
app.get('/api/articles', function(req, res) {


res.writeHead(200, {
    "Content-Type": "application/json"
});
// use mongoose to get all feeds in the database
Feed.find(function(err, feeds) {
    // if there is an error retrieving, send the error. nothing after     res.send(err) will execute
    if (err)
        res.send(err);

    feeds.forEach(function(feedModel) {
        //for each feed in db get articles via feed-read module
        feed(feedModel.url, function(err, articles) {
            articles.forEach(function(articleModel) {
                console.log(JSON.stringify(articleModel));//works!!
                res.write(JSON.stringify(articleModel));//doesnt produce output.
            });
        });
    });
}); //end find function
res.end();
}); //end api call

【问题讨论】:

  • 嗨!经过一些修补后,我通过删除 res.writeHead 和 res.end 行使其工作。显然,我将使用前面的代码触发两个 writeHead,并通过删除行节点或 express 将“自动”修复标题。
  • 我得到了这个想法,然后发布:stackoverflow.com/questions/17628052/…

标签: javascript json node.js express


【解决方案1】:

你需要end()在最后的回调没有。

res.end(JSON.stringify(articleModel));

【讨论】:

  • 好的。试过了。现在第一个提要实际上出现了,但其余的都没有。我在想那是因为我们实际上在处理完其余的提要之前就提前结束了?我如何将所有 articleModels 合并到一个列表中,然后只使用一个 res.end 语句将响应发送回来?
  • 那么你需要promises,或者一个管理回调的机制。但这是一个单独的问题。
【解决方案2】:

经过一些修改后,我通过删除 res.writeHead 和 res.end 行使其工作。显然,我将使用前面的代码触发两个 writeHead,并通过删除行节点或 express 将“自动”修复标题。 /斯蒂芬

【讨论】:

猜你喜欢
  • 2012-05-26
  • 1970-01-01
  • 2015-08-04
  • 1970-01-01
  • 2015-07-09
  • 1970-01-01
  • 1970-01-01
  • 2016-09-07
  • 2014-01-04
相关资源
最近更新 更多