javascript - 如何生成多个response.write :s with json in node. js/express?

标签 javascript json node.js express

从 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/

相关文章:

javascript - 在点击时显示社交图标的子列表

javascript - 更新网格行元素

javascript - Object.prototype.valueOf() 方法

c# - ASP.NET ActionResult 对本地主机和托管的 Azure Web 服务提供不同的响应

Node.js "Server listening on port 3000",但我无法在浏览器中查看它?

javascript - 如何结合 Passport 和 Angular 用户界面路由

javascript - 如何使用 Jest 在 typescript 中模拟 Date 对象?

javascript - 如果新选项值尚不存在,则动态地将新选项值添加到选择框中

c# - JToken 数组到数据表 C#

java - 自动将 JSON 字节从 RabbitMQ 队列转换为对象