Reputation: 2387
I keep getting this error message: Can't set headers after they are sent
. I'm pretty new. This is a simple to-do list app that saves each item to mongodb, and displays each item on the page. It also has the ability to remove items. Everything seems to work okay, but I still keep getting this message. The error message occurs every time I try to use delete item route. Like I said, it works like I expect it to. It removes the item from the list, and from the database, but I still keep getting this error message. Here's what the delete route looks like:
app.delete('/:id', function(req, res){
var removal = req.params.id;
MongoClient.connect(dbUrl, function(err, db){
var list = db.collection('list');
list.remove({ _id: ObjectId(removal)}, updateList(res));
});
res.redirect('/');
});
//update list displayed on page -- to be used via callback after db change
function updateList(res){
MongoClient.connect(dbUrl, function(err, db){
var list = db.collection('list');
list.find({}).toArray(function(err, docs){
res.render('index', { title: 'To do:', list: docs });
});
});
};
I used res.redirect('/')
to make it so the URL shown in the address bar doesn't show the ObjectId of each item I remove, but it seems like that might be the problem, because when I get rid of it, the error doesn't come up. But I don't want that ID number showing up at the top. Doing it this way seems to work. Why does it give me an error message? Is there another way to accomplish this?
Upvotes: 0
Views: 262
Reputation: 514
Probably this piece of code going to help you. But you need to learn more about callbacks, functions and how to use them...
app.delete('someRouteName/:id', function(req, res){
var removal = req.params.id;
MongoClient.connect(dbUrl, function(err, db){
var list = db.collection('list');
list.remove({ _id: ObjectId(removal)}, function(error){
if(error){
// Handle error
}
else{
list.find({}).toArray(function(err, docs){
if(err){
// Handle error
}
else{
return res.render('index', { title: 'To do:', list: docs });
}
});
}
});
});
});
~ Cheers
Upvotes: 1
Reputation: 10687
You probably need to use return
before res.redirect
return res.redirect('/');
Upvotes: 0