简体   繁体   中英

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

Having some trouble with generating multiple response.write:s from an api call in node.js. Here is the code.

 // 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 end()

res.end(JSON.stringify(articleModel));

After some tinkering I got it to work by removing the res.writeHead and res.end lines. Apparently I will trigger two writeHead with the previous code and by removing the lines node or express will "automagically" fix the headers. /Stefan

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM