Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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');
    }
};
like image 400
Tam2 Avatar asked Jun 08 '16 15:06

Tam2


People also ask

What causes Err_too_many_redirects?

The ERR_TOO_MANY_REDIRECTS error occurs when the browser is redirected to a different URL, which in turn points back to the original one, creating a redirection loop.

Why does Safari keep saying too many redirects?

This feature, unfortunately, can cause interruptions when a site uses an authentication service such as Google, which can lead to an error known as “Too many redirects”. This error occurs as Safari's new ITP is blocking authentication checks between Google and services such as Securly.


2 Answers

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);
like image 162
robertklep Avatar answered Nov 07 '22 16:11

robertklep


Classical error would stand in your configuration of Apache/Nginx. In your code, you seem to be using port 80, which I believe you are not using and therefore you would be proxying your requests through Apache or Nginx.

(can't comment so even though this is a poor answer, I will update it accordingly on further comments)

like image 21
rels Avatar answered Nov 07 '22 14:11

rels