Why does it say "ERR_HTTP_HEADERS_SENT"

I’m trying to build a MERN stack based blogging site and as all the site shows the list of blogs appearing upon request, I tried doing it this way

app.get("/User/", (req, res) => {
    db.getDB().collection("posts").find({}).toArray((err, posts) => {
        if (err) { 
            return res.send("Error fetching data");
        } else {
            posts.forEach(post => {
                res.send(post.post)                
            });
        }
    })
})

and I was successful in getting this output


And also the error Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:485:11)

It would mean a lot if anybody could explain me why this happens. Thanks in advance.

The key hint here is the error is mentioning “headers sent”, meaning your trying to send more data back to the client, but you already sent data. When it comes to http requests (like the kind express handles) there is a request and a response, so its a 1 to 1. What your currently doing is taking the request, making a db call then making multiple responses. The relevant code is these lines:

posts.forEach(post => {
  res.send(post.post)                
});

Your trying to send data back in a loop with wont work and will give you errors like this.

If you want to return data you have to return it 1 time, so I recommend wrapping your posts into an array and returning that:

const data = posts.map(post => post.post);
// Send an array of data
res.send(data);
2 Likes

Hello!

That’s because you cannot send more than one response to the client. In your case, you’re sending multiple responses when iterating over the posts:

posts.forEach(post => {
    res.send(post.post)                
});

What you should do is send the entire array or build a different array with only the posts:

res.send(posts.map(i => i.post))

Hope it helps :slight_smile:,

Regards!

2 Likes

Thank you for your reply. I understood what’s wrong!!

Thank you so much for making me understand.!!

Since both the replies are a solution I’m not marking them!!

1 Like

2 posts were split to a new topic: Please help me with this problem