【发布时间】: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