javascript - 刷新页面时,AngularJS 路由返回 404 错误

标签 javascript angularjs angularjs-routing html5mode

我是 angularJS 的新手,我喜欢用它编码。我目前正在使用 angularJS 构建一个门户网站,并且我的每个页面都使用 ngRoute。它对我来说工作正常,但当我尝试刷新页面时,它返回一个 404 错误/找不到页面。对于这个问题我该怎么办?这是我的代码:

var app = angular.module("CVSRRC", ['ngMaterial','ngRoute']);

app.controller('CVSRRC-CTRL', function($scope, $http, ...){
    // some codes here...
});

app.config(function($routeProvider, $locationProvider){
    $locationProvider.html5Mode(true).hashPrefix('!');

    $routeProvider
    .when('/', {
        templateUrl: '_pages/home',
        controller: 'homeCTRL',
        resolve: {
           delay: function($q, $timeout){
                var delay = $q.defer();
                $timeout(delay.resolve, 1000);
                return delay.promise;
           }
        }  
    })
    ...etc...
    .otherwise({
         redirectTo: '/'
    });
});

和我的HTML

<html>
   <head>
       <base href="/cvsrrc/" />
   </head>
   <body ng-app="CVSRRC" ng-controller="CVSRRC-CTRL">

      <div class="row" id="main">
        <div ng-view ng-show="statechange"></div>
        <div ng-show="!statechange" cvsrrc-resolve>
            <div id="_loader_"></div>
        </div>
    </div>

   <a href="about-us">About</a>
   <a href="login">login</a>
   //etc
   </body>
 </html>

这是我的 .htaccess 看起来像

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]
ErrorDocument 404 http://localhost/cvsrrc/page-not-found

最佳答案

自从您使用过 <base href="/cvsrrc/" />$locationProvider.html5Mode(true).hashPrefix('!');您的网址已删除#!来自 url 并添加 cvsrrc/。因此,如果您从应用程序重定向应用程序,它将起作用。

但是当您重新加载页面时,它会尝试使用带有 cvsrrc/的 url 来查找实际上不存在的路径。

所以你必须在服务器上使用重写模块来告诉将 cvsrrc/重定向到 #!/

关于javascript - 刷新页面时,AngularJS 路由返回 404 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41930550/

相关文章:

javascript - Django 和 Mustache 使用相同的模板语法

javascript - 如何使用用户输入的关键字在 Node.js 中执行 Twitter API 搜索

javascript - Angularjs 编辑和更新并添加其他数据

angularjs - href ="#"导致位置地址改变,我们可以避免吗?

javascript - 使普通对象可迭代。(javascript)

javascript - 根据请求数据动态创建 SVG

javascript - Meteor.js 应用程序不支持 IE 9

javascript - Angular : ng-change mixed with jQuery not firing on second change

javascript - 如何全局解决依赖关系(从服务器预加载当前用户)

angular ui路由器状态更改时触发的ios地址栏