如何在node.js/express中用json生成多个响应.write:s

How to generate multiple response.write:s with json in node.js/express?

本文关键字:响应 write json node js 中用 express      更新时间:2023-09-26

在生成多个响应时遇到一些问题。请从node.js中的api调用中写入: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));

经过一些修补,我删除了res.writeHead和res.end行,使其正常工作。显然,我将用前面的代码触发两个writeHead,通过删除行节点或express将"自动"修复头。/Stefan