Reputation: 345
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');
}
};
Upvotes: 7
Views: 16221
Reputation: 54
Actually, this type of error occurs, when a website creates a redirect loop. One redirect leads to another and creates a chain that redirects back to itself in a loop, and directs the user between different addresses infinitely.
For example look at this contoller which handle the url '/users/sign_in' request :
module.exports.sign_in=(req,res)=>{
if(req.isAuthenticated())
{
return res.redirect('/question/all_questions');
}
return res.redirect('/users/sign_in');
}
So here when user want to sign in then at that time this code handle that request.In this code first we check whether the user is logged in or not.If user is already logged in then we can redirect to the given url as "/question/all_questions".
But what if user is not logged in then we again send the request '/users/sign_in',then again it will check whether the used logged in or not and if not logged in then it again send the request '/users/sign_in'.So you clearly see that that it will actually creating an infinite loop if the user is not already logged in.So when this type of situation occur at that time browser automatically break this infinte loop and give error as "too many redirects". So to solve this problem instead of writing
return res.redirect('/users/sign_in');
we have to render the page as
return res.render('sign_in');
instead of redirecting the url and created the infinite loop.
So i think you have to look at your code carefully that whether is there any inifinte loop is created of which i am taking about at above.
Upvotes: 0
Reputation: 203484
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);
Upvotes: 10
Reputation: 745
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)
Upvotes: 1