AngularJS $routeProvider:路由不起作用

AngularJS $routeProvider: routing does not work

我创建了一个用于身份验证的登录页面。根据认证的结果,重定向到不同的页面。

//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');
        });
    }
}]);

应用在下面config.js中与路由一起定义。 //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' 
        });
});

文件结构:

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

当我提交登录表单时,没有重定向到“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.

我在 root 下启动 node.js。在 Chrome 中的 "network" 选项卡中,它显示 "config.js" 已加载。为什么路由不起作用?

如果不想在angular路由中使用#,需要开启Html5模式。

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);
});

如果这不起作用,您可能必须通过将其放在页首部分来设置页面的基础。

<base href="/">