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);