Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

208
Views
express redirect error Can't set headers after they are sent

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)

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report

0

You just have to remove this line and your /listall route should work:

res.redirect('/listall')
over 4 years ago · Santiago Trujillo Report

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!