I have a node/express api with a simple call that works the first time it's called, but not the second. The result is basically null, so it should always respond with 'No posts found', which it does the fist time it's called.
export const getAllBlogs = async (req, res) => {
const posts = await Blog.find({});
if(posts == 0) res.send('No posts found');
res.send(posts);
};
What am I missing that would cause the following error: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
CodePudding user response:
res.send is called twice, this is the reason of error.you can change it like this.if(posts == 0) { res.send('No posts found'); } else { res.send(posts); }
CodePudding user response:
It happens because res.send() used twice in your route if posts == 0. You can change it this way:
export const getAllBlogs = async (req, res) => {
const posts = await Blog.find({});
if(posts == 0) {
res.send('No posts found');
else {
res.send(posts);
}
};
