AngularJS:当使用启用Html5模式的Angular Ui Router时,页面加载失败

AngularJS: Page reload fails when using Angular Ui Router with Html5 mode enabled

本文关键字:Router Ui 失败 加载 Angular 启用 模式 Html5 AngularJS      更新时间:2023-09-26

我在我的Angular应用中使用的是Angular UI Router,并且我已经启用了HTML5模式,通过在配置中使用$locationProvider来删除URL中的#。

angular.module('myApp', ['ui.router'])
 .config(function($stateProvider, $urlRouterProvider, $locationProvider) {
    $urlRouterProvider.otherwise('/');
    $stateProvider
       .state('home', {
            url: '/',
            templateUrl: 'views/home.html',
            controller:'HomeController'
        })
        .state('about', {
            url: '/about',
            templateUrl: 'views/about.html',
            controller:''
       })
       .state('skills', {
            url: '/skills',
            templateUrl: 'views/skills.html',
            controller: ''
       })
       .state('projects', {
            url: '/projects',
            templateUrl: 'views/projects.html',
            controller: 'ProjectsController'
       })
       .state('contact', {
            url: '/contact',
            templateUrl: 'views/contact.html',
            controller: ''
       });
    $locationProvider.html5Mode(true);
});

我还设置了

<base href="/">

标记也在index.html文件中。路由工作正常,我可以导航到页面和#被删除,但当我使用浏览器上的重新加载按钮刷新页面时,我得到一个404错误页面。

我正在使用Webstorm IDE进行开发。有人能为我提供一个解决方案吗?

启用HTML5模式你的url哈希#变成了哈希#!然后它在浏览器上返回url而不带hashbang。虽然浏览器上的url是

http://www.example.com/about

实际的hashbang url是这样的:

http://www.example.com/#!/about

尝试根据此更改您的htaccess文件。它应该位于index.html所在的公共目录,

RewriteEngine On  
  # If an existing asset or directory is requested go to it as it is
  RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
  RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
  RewriteRule ^ - [L]
  # If the requested resource doesn't exist, use index.html
  RewriteRule ^ /index.html