AngularJS: ngRoute causing too many redirects error?

Issue

index.html:

<body ng-app="myApp">
    <div ng-controller="MainController">
        ... {{ title }} ...
            <div class="collapse navbar-collapse">
                <ul class="nav navbar-nav">
                    <li><a href="#/register" ng-hide="authenticated">Register</a></li>
                    <li><a href="#/login" ng-click="login">Login</a></li>
                    <li><a href="#" ng-click="logout">Logout</a></li>
                </ul>
            </div>
        ...
        <div ng-view></div>
    </div>
</body>

Ellipses to shorten the html. MainController just sets $scope.title = “My App”

In my angular module, I use ngRoute and implement routing as such:

app.config(function($routeProvider)
{
    $routeProvider 
    .when('/',
    {
        controller: 'MainController',
        templateUrl: 'main.html'
    })
    .when('/login',
    {
        controller: 'AuthenticationController',
        templateUrl: 'login.html'
    })
    .when('/register',
    {
        controller: 'AuthenticationController',
        templateUrl: 'register.html' 
    });
});

My AuthenticationController just defines the login and register functions to make post calls to the server, but I am not making those calls since I am not clicking login or register.

Everything works smoothly in terms of swapping out ng-view for the appropriate view, but when I open the console, every time I switch the view, I get a “localhost:3000/login” too many redirects. I find it odd because regardless if I click register, login, logout, it always says “localhost:3000/login” too many redirects. This is within the context of an express framework, but I don’t think it is an error on my server side because it’s doesn’t appear to be hitting my app.use(‘/’,index) router in express. Is this normal?

EDIT: Here is my index router:

var express = require('express');
var router = express.Router();

router.get('/',function(req,res,next)
    {
        return res.render('index', { title: 'SERVER TITLE' });
    }
);

module.exports = router;

In app.js:

app.use('/', index); 
app.use('/auth', authenticate); 

app.all('*',function(req,res,next)
{
  if(req.isAuthenticated())
  {
    return next();
  }
  else
  {
    res.redirect('/login');
  }
});

Solution

The problem was that my client side routing was faulty, so my requests ended up to the server, which ended up in multiple redirects.

Answered By – PDN

Answer Checked By – Candace Johnson (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.