1

下面的代码来自 AngularJs 教程,我稍作修改。我希望从 url 中删除哈希。我实际上成功了,但现在我有其他问题。

当我使用链接本地主机时,它工作得很好并将我重定向到本地主机/电话。但如果我尝试使用直接链接 localhost/phones,浏览器会抛出 404 错误。为什么呢?

代码:

var phonecatApp = angular.module('phonecatApp', [
'ngRoute',
'phonecatControllers'
]);

phonecatApp.config(['$routeProvider', '$locationProvider' ,function($routeProvider,       $locationProvider) {
$routeProvider
    .when('/phones', {
        templateUrl : 'partials/phone-list.html',
        controller : 'PhoneListCtrl'
    }).
    when('/phones/:phoneId', {
        templateUrl : 'partials/phone-detail.html',
        controller : 'PhoneDetailCtrl'
    }).
    otherwise({
        redirectTo : '/phones'
    });

    $locationProvider.html5Mode(true).hashPrefix('!');
}])
4

1 回答 1

3

您必须为此处理 url 重写服务器端。

根据您的服务器,您必须添加:

在 apache 中(例如 .htaccess):

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteRule !\.\w+$ index.html [L]
</IfModule>

如果您使用 grunt 和 grunt-contrib-connect,只需使用此 regexp 添加中间件(modRewrite):

connect: {
  options: {
      port: 9002,
      hostname: 'localhost' // put here any ip if you want external access
  },

  dev: {
      options: {
          middleware: function(connect) {
              return [
                  //modRewrite is used to handle properly angularjs' html5 mode
                  modRewrite([
                      '^[^\\.]*$ /index.html [L]'
                  ])
              ]
          }
      }
  }
}

ps:在这种情况下,您的主要入口点必须是 index.html 。

pps:您可能需要针对特定​​情况调整此正则表达式。

于 2014-03-20T08:04:26.180 回答