AngularJs routeProvider 404

2020-04-18 05:54发布

Code bellow is from AngularJs tutorials and little bit modified by me. I wish to remove hash from url. I actually succeed, but now I have other problem.

When I use link localhost, it works just fine and redirect me to localhost/phones. But in case, that I try with direct link localhost/phones, browser throws me 404 error. Why is that so?

Code:

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

1条回答
狗以群分
2楼-- · 2020-04-18 06:30

You have to handle url rewriting server-side for that.

Depending on your server, you'll have to add:

In apache (.htaccess for example) :

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

If you're using grunt and grunt-contrib-connect, just add a middleware (modRewrite) with this regexp :

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: that your main entry point must be index.html in this case.

pps: you may have to tune this regexp for specific cases.

查看更多
登录 后发表回答