0

In my app.js I do this

app.use(function(req, res, next){

  if(!req.user){
    res.redirect('/login_');
  }
  next();
})

I don't see anything wrong and in route/index.js I do

router.get('/login_', function(req, res) {
    res.render('login', { user : req.user });
});

But I got error of throw new Error('Can\'t set headers after they are sent.'); I know this is caused by the request is not ended but what's wrong with my code above? clueless with this error.

full code of route/index.js http://pastebin.com/kT2QfnjL

Maria Jane
  • 2,353
  • 6
  • 23
  • 39

2 Answers2

2

This is caused because when the code tries to send the response after the response is sent.

Reference:

Error: Can't set headers after they are sent to the client

Community
  • 1
  • 1
Shankar Shastri
  • 1,134
  • 11
  • 18
1

return and redirect to solve this issue

app.use(function(req, res, next){

  if(!req.user){
    return res.redirect('/login_');
  }
  next();
})
Lekhnath
  • 4,532
  • 6
  • 36
  • 62