从 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
最佳答案
您需要在回调 no 的末尾添加 end()
。
res.end(JSON.stringify(articleModel));
关于javascript - 如何生成多个response.write :s with json in node. js/express?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31230910/