cshermans
cshermans

Reputation: 105

res.redirect Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

Keep getting this error pointing back to a res.redirect... I thought adding a 'return' would fix it since it allows the middleware to end but error persisting

heres the function

app.post('/login', (req,res) => {
   //set this up with passport ideally... auth with db 
   var username = req.body.email
   var password = req.body.password
  
   User.findOne({email:username})
   .then(user => {
      if(user) {
         bcrypt.compare(password, user.password, function(err, result) {
            if(err) {
               //maybe send this back in res json?
               console.log(err)
               return res.redirect('/login')
            }
            else if(result){
               //let token = jwt.sign({name:user.name}, )
               req.session.user = user.dataValues
               console.log('Login successful')
               return res.redirect('/dashboard');       //error happening here
            }else {
               console.log('Password does not match')
               return res.redirect('/login')
            }
         })
      }
   })
   res.redirect('/')
})

And here is my output

Login successful
undefined:0



Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:533:11)
    at ServerResponse.header (/Users/sherm/Documents/daily_email/node_modules/express/lib/response.js:771:10)
    at ServerResponse.location (/Users/sherm/Documents/daily_email/node_modules/express/lib/response.js:888:15)
    at ServerResponse.redirect (/Users/sherm/Documents/daily_email/node_modules/express/lib/response.js:926:18)
    at /Users/sherm/Documents/daily_email/server.js:79:27 {
  code: 'ERR_HTTP_HEADERS_SENT'
}
npm ERR! code ELIFECYCLE

Upvotes: 1

Views: 2539

Answers (1)

Δ O
Δ O

Reputation: 3710

The problem is, you're calling res.redirect('/') (line 27 of your example), before User.findOne(...).then is triggered. Hence, in case user is found, your result headers are already sent by that redirect.

Instead, try this:

...
User.findOne({email:username})
   .then(user => {
      if(user) {
        ...
      } else
        res.redirect('/')
   })
...

Upvotes: 1

Related Questions