I usually see this error when I'm using res
multiple times in my Express route by mistake. Be sure that in route handler (function) you are only using res
once.
For example
app.get('/foo', doFoo);
function doFoo(req, res) {
res.send('foo');
res.send('bar');
}
won't work since you're trying to use res twice which internally calls res.end()
if I'm not mistaken.
Edit: As it turns out, I think I see the problem in your code.
// create a todo, information comes from AJAX request from Angular
Todo.create({text : req.body.text}, function(err, todos) {
if (err)
res.send(todos);
// get and return all the todos after you create another
Todo.find(function(err, todos) {
if (err)
res.send(err)
res.json(todos);
});
});
Here, you're using res.send(todos)
in the event that you receive an error from your first call to Todo.create
. Assuming you do receive an error here, your code will still attempt Todo.find
. Once that happens, it will then try res.json(todos)
thereby firing two responses and resulting in the error that you see about not being able to set response headers after they're already sent. I think you can fix your code by using actual else
statements to ensure you don't send two responses.
Todo.create({text:req.body.text}, function(err, todos){
if (err) {...}
else {
.. your else code here
}
});