Express.js Routing error: Can't set headers after they are sent

Solution 1:

You need to add the 'return' so that you don't reply twice.

// save post and check for errors
post.save(function(err) {
    if (err) {
        return res.send();
    }
    res.json({ message: 'post created!' });
});

Solution 2:

That particular error message is pretty much always caused because of a timing error in the handling of an async response that causes you to attempt to send data on a response after the response has already been sent.

It usually happens when people treat an async response inside an express route as a synchronous response and they end up sending data twice.


One place I see you would get this is in any of your error paths:

When you do this:

       // save post and check for errors
        post.save(function(err) {
            if (err)
                res.send();

            res.json({ message: 'post created!' });
        });

If post.save() generates an error, you will do res.send() and then you will do res.json(...) after it. Your code needs to have a return or an else so when there's an error you don't execute both code paths.

Solution 3:

So, this can happen in Express when attempting to send res.end twice which res.send and res.json both do. In your if(err) block you'll want to return res.send() as res.send runs asynchronously and res.json is getting called as well. I'm wondering if you're getting an error in your delete route? Hope this helps.

Best!

Solution 4:

You are using res.send() or res.json() twice in the same request

this send the headers first, followed by body of the response and then headers again. req.next is usually not a function, next is rather passed as a third argument of the middleware. Use that if you want to drop to the next middleware. (assuming you are using Express framework)