奇怪的angularjs路线行为

时间:2017-12-29 18:38:17

标签: javascript angularjs

我在angularjs app上有以下路线:

 angular.module('index').config(['$routeProvider', '$locationProvider',
                   function indexRouteConfig($routeProvider, $locationProvider) {

   $locationProvider.html5Mode(true);

   var routeToUserHomePage = ['$injector', function routeToUserHomePage($injector) {
       var $location = $injector.get('$location');
       //somecode

       $location.url('/unauthorized'); // this works
   }

   $routeProvider
     .when('/', {
        templateUrl   : 'app/custom/templates/customTemplate.html',
        controller    : 'customTemplateController',
        resolve       : { routeToUserHomePage: routeToUserHomePage }
    })
    .when('/unauthorized', {
        templateUrl   : 'app/custom/templates/customTemplate.html',
        controller    : 'customTemplateController'
    })
    .otherwise({
        resolve : { routeToUserHomePage: routeToUserHomePage }
    });

如果我访问了网址http://localhost:8090/,它就能完美运行,并重定向到unauthorized屏幕。

但是,如果我转到浏览器并输入http://localhost:8090/unauthorized,我会从网络服务器收到错误404 Not Found 。它甚至没有达到“其他”路线。我在这里失踪了什么?

我在index.html文件上有<base href="/">标记。

2 个答案:

答案 0 :(得分:0)

创建一个单独的控制器和模板,然后在该控制器内写入逻辑

.otherwise ({
    url: '/unauthorized',
    controller: 'error',
    templateUrl: 'templateUrl.html',
});

function error($location) {
 // write whatever your logic
}

答案 1 :(得分:0)

这是因为您已启用html5Mode并且您在服务器上没有它所需的内容。

  

服务器端使用此模式需要在服务器端重写URL,基本上您必须重写所有指向应用程序入口点的链接(例如index.html)

来源:AngularJS HTML5 Mode - How do direct links work without server specific changes?