ui-router的$ urlRouterProvider.otherwise与HTML5模式

Kev*_*ith 5 html5 angularjs angular-ui-router

请考虑ui-router的wiki中的以下略微修改的代码.

var myApp = angular.module('myApp',['ui.router']);

myApp.config(function($stateProvider, $urlRouterProvider, $locationProvider) {
    // for any unmatched url
    $urlRouterProvider.otherwise("/state1");

    $locationProvider.html5Mode(true);

    // now set up the states
    $stateProvider
        .state('state1', {
            url: '/state1',
            templateUrl: "partials/state1.html"
        })
        .state('state1.list', {
            url: "/list",
            templateUrl: "partials/state1.list.html",
            controller: function($scope) {
                $scope.items = ["A", "List", "of", "Items"];
            }
        })
        .state('state2', {
            url: "/state2",
            templateUrl: "partials/state2.list.html",
            controller: function($scope) {
                $scope.things = ["a", "set", "of", "things"];
            }
        })
});
Run Code Online (Sandbox Code Playgroud)

运行python 3的SimpleHttpServer,我404 error在尝试访问时得到:http://localhost:8000/state1234324324.

为什么没有$urlRouterProvider.otherwise("/state1");重定向所有未知路由/state1,根据这个问题,已经定义state了与/state1url 关联?

ash*_*shu 9

这是因为当您使用"/ state123413"等网址访问服务器时,它将直接返回404响应(客户端没有路由发生).

你需要做的是拥有一条捕获路线.例如,你可以做快递

app.get('/*', function(req, res){
   res.render('defaulttemplate')   
}
Run Code Online (Sandbox Code Playgroud)

这将强制在客户端进行路由.有关常用服务器的信息,请参阅ui router faq以设置catchall路由.