【问题标题】:AngularJs routeProvider 404AngularJs routeProvider 404
【发布时间】:2014-03-20 07:53:24
【问题描述】:

下面的代码来自 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('!');
}])

【问题讨论】:

    标签: angularjs location-provider


    【解决方案1】:

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

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

    在 apache 中(例如 .htaccess):

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

    如果您使用 grunt 和 grunt-contrib-connect,只需使用此正则表达式添加中间件 (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:您可能需要针对特定​​情况调整此正则表达式。

    【讨论】:

      猜你喜欢
      • 2016-07-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-10
      • 1970-01-01
      • 1970-01-01
      • 2014-06-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多