app.get('/', function (req, res) {
mongoose.connect('mongodb://localhost/todo-list')
Todo.find({completed: false}, function (err, todos) {
if (err) throw err
res.render('homepage', {
allTodos: todos
})
mongoose.disconnect()
})
})
//
app.post('/create', function (req, res) {
// console.log(req.body)
// res.send(req.body)
todosController.create(req, res)
})
app.get('/listall', function (req, res) {
res.redirect('/listall')
todosController.list(req, res)
})
// and below is my controller
function list (req, res) {
if (!mongoose.connection.db) mongoose.connect('mongodb://localhost/todo-list')
Todo.find({}, function (err, todos) {
if (err) throw err
res.render('listall', {
allTodos: todos
})
mongoose.disconnect()
})
}
can someone tell me how to fix this >.< express shows error "Can't set headers after they are sent." at ServerResponse.setHeader (_http_outgoing.js:371:11)
The problem comes from trying to send request to user twice (via render and redirect), here:
app.get('/listall', function (req, res) {
res.redirect('/listall')
todosController.list(req, res)
})
Youredirect user to listall view, but then you are invoking list method, which tries to render another page here:
res.render('listall', {
allTodos: todos
})
You have to decide, if you want to redirect user to page, or render it to him, and remove one of those above.
You just have to remove this line and your /listall route should work:
res.redirect('/listall')
Your function todosController.list(req, res) seems to have also a res.send/res.redirect ... method. But you can only send a response once so if there are other res. methods in your request flow you get this error.
You can redirect the user from your todosController.list method and remove it from here app.get('/listall', function (req, res) {
res.redirect('/listall')
todosController.list(req, res)
})
But take care not to send res. more than once in one single req. flow.