Tamoor Malik Tamoor Malik - 6 months ago 171
Node.js Question

node-express too many redirects

I've got my routes set up like below

When i navigate to 'http://localhost/' i get an error saying 'localhost redirected you too many times' and the URL of the page (showing in the URL bar of the browser) is http://localhost/!/dashboard - so it does look like it is being redirected, but i cannot see why it's getting stuck in an infinite loop

// Public Routes
app.use('/', function(req,res){
res.redirect('/!/dashboard');
});
app.use('/login', routes.login);
app.use('/!/dashboard', isLoggedIn, routes.dashboard);

// Check If Logged In
function isLoggedIn(req,res,next){
if (req.isAuthenticated()){
return next();
} else {
res.redirect('/login');
}
};

Answer

You shouldn't use app.use('/', ...), because that will match any URL starting with a /.

Instead, use app.all:

app.all('/', function(req,res){
  res.redirect('/!/dashboard');
});
app.use('/login', routes.login);
app.use('/!/dashboard', isLoggedIn, routes.dashboard);