Nodejs: Can not set headers after they are sent

1

Good I have an error in Node that I do not understand because it happens:

class HomeController {

getViewLogin(req, res, next) {
    if(req.isAuthenticated())
        res.redirect('/index');
    res.render('singIn', {
        title: 'Login'
    });
}

getViewIndex(req, res, next){
    //console.log(req.user.nombres);
    //console.log(req.isAuthenticated());
    if(!req.isAuthenticated())
        res.redirect('/');
    res.render('index', {
        title: 'Bienvenido',
        user: req.user
    });
}
}module.exports = HomeController;

I am simply redirecting when the user is logged in, this code works but returns that error to me. Thanks.

    
asked by Joseph Leon 13.03.2017 в 17:26
source

1 answer

4

This error occurs when you try to set response headers when it has already been sent to the client. Try to always use if/else to define a strict flow. Your code does not prevent res.render from being called after redirecting to /index or vice versa.

Also, it is not necessary to have two middlewares, just one is enough:

  

Do not render from a middleware. Instead, rediects to a path where that view is rendered.

app.use((req, res, next) => {
  if (req.isAuthenticated()) {
    if (req.url.includes('/login') {
     res.redirect('/index');
    }
  } else {
    res.redirect('/login');
  }
});
    
answered by 13.03.2017 / 17:39
source