I\'m not really sure why I\'m getting this error. It\'s a simple API built on express.js to be able to add and remove posts. The error occurs when I trigger the delete route
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)
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!' });
});
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!
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.
Just for the sake of completeness I will also mention that:
Sometime problem may be in a the middleware you may be using by calling
app.use
.
After checking for obvious errors as mentioned in previous answers:
You should remove all the app.use
statement then reintroduce them one by one, to find problematic module.
If you are using res.send() inside any loop, then you need to break it after the use of res.send(). So that it won't allow resetting of the res headers again and again.
for e.g :
for(){
if(){
res.send();
break;
}
else(){
res.send();
break;
}
}
In my case this is the problem and I solved it like this.
Hope it may help someone in future.
Thanks