1

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
2
  • Hi! 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. Commented Jul 5, 2015 at 20:10
  • I got the idea from to post: stackoverflow.com/questions/17628052/… Commented Jul 5, 2015 at 20:10

2 Answers 2

1

You need to end() inside the callback no at the end.

res.end(JSON.stringify(articleModel));
Sign up to request clarification or add additional context in comments.

2 Comments

Ok. tried that. Now the first feed actually shows up but not the rest. I am thinking thats because we actually end prematurely before we are done processing the rest of the feeds? how would I merge all the articleModels in a list then just using the one res.end statement to send the respond back?
Then you'll need promises, or a mechanism to manage callbacks. But that is a separate question.
0

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

1 Comment

I got the idea from to post: stackoverflow.com/questions/17628052/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.