Javascript 如何生成多个响应。在node.js/express中使用json编写:s?
从node.js中的api调用生成多个响应时遇到问题。write:s。这是代码Javascript 如何生成多个响应。在node.js/express中使用json编写:s?,javascript,json,node.js,express,Javascript,Json,Node.js,Express,从node.js中的api调用生成多个响应时遇到问题。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, feed
// 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
您需要end()
在末尾的回调编号中
res.end(JSON.stringify(articleModel));
经过一些修补后,我通过删除res.writeHead和res.end行使其工作。显然,我将使用前面的代码触发两个writeHead,通过删除lines节点或express将“自动”修复头。
/斯蒂芬好的。我试过了。现在第一个feed实际出现了,但其余的都没有。我想这是因为我们在处理完剩下的提要之前就提前结束了?我如何将所有articleModels合并到一个列表中,然后仅使用one res.end语句发送回响应?然后您将需要一个或一个机制来管理回拨。但这是另一个问题。嗨!经过一些修补后,我通过删除res.writeHead和res.end行使其工作。显然,我将使用前面的代码触发两个writeHead,通过删除lines节点或express将“自动”修复标题。我的想法来源于:我的想法来源于: