Search code examples
angularjsangularjs-routing

AngularJS $routeProvider: routing does not work


I created a login page for authentication. Based on the result of authentication, it redirects to different pages.

//controller.js

app.controller("LoginCtrl", ['$scope', '$location', 'loginFactory', function($scope, $location, loginFactory){
    $scope.authenticate = function() {
        loginFactory.login($scope.username, $scope.password)
        .then(function(response) {
            $location.path('/home');
        }, function errorCallBack(response) {
            console.log("Failed auth");
            $location.path('/login');
        });
    }
}]);

The app is defined in the following config.js together with routing. //config.js

var app = angular.module('ristoreApp', ['ngRoute']);
app.config(function ($routeProvider, $locationProvider, $httpProvider) {
    $routeProvider
        .when('/', {
            redirectTo: '/home'
        })
        .when('/login', { 
            templateUrl: 'views/login.html', 
            controller: 'LoginCtrl' 
        })
        .when('/home', { 
            templateUrl: 'views/home.html', 
        })
        .otherwise({ 
            redirectTo: '/login' 
        });
});

The structure of files:

root/
    js/ -- config.js
        -- authentication/ -- controller.js
    views/ -- home.html
           -- login.html

When I submit the login form, instead of redirecting to "http://127.0.0.1:8081/views/login", it redirects to "http://127.0.0.1:8081/views/login#/login". Plus "http://127.0.0.1:8081/login" returns 404.

I start node.js under root. From the "network" tab in Chrome, it shows "config.js" is loaded. Why doesn't the routing work?


Solution

  • If you do not want to use the # in angular routing, you need to enable Html5 mode.

    var app = angular.module('ristoreApp', ['ngRoute']);
    
    app.config(function ($routeProvider, $locationProvider, $httpProvider) {
        $routeProvider
            .when('/', {
                redirectTo: '/home'
            })
            .when('/login', { 
                templateUrl: 'views/login.html', 
                controller: 'LoginCtrl' 
            })
            .when('/home', { 
                templateUrl: 'views/home.html', 
            })
            .otherwise({ 
                redirectTo: '/login' 
            });
         $locationProvider.html5Mode(true);
    });
    

    if that is not working, you may have to set your base on the pages by putting this in the head section.

    <base href="/">