AngularJS关于html5mode页面刷新错误的页面

时间:2018-03-17 15:11:04

标签: angularjs ngroute html5mode

我正在使用w3schools路线示例制作一个简单的网站。我的项目文件夹是wamp/www/angular/7base href="/angular/7/"。但是当我在angular/7/red页面刷新我的页面时,刷新显示NOT Found。请提出建议或纠正我的错误,以下是代码。

<!DOCTYPE html>
<html ng-app="myApp">
<base href="/angular/7/">
<!--script>document.write('<base href="' + document.location + '" >');</script-->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.js"></script>
<body>
    <a href="./">Main</a> | <a href="./red">Red</a> | <a href="green">Green</a> | <a href="blue">Blue</a>
    <div ng-view></div>
    <script src="script.js"></script>
</body>
</html>

var app = angular.module("myApp", ["ngRoute"]);
document.getElementsByTagName("base")[0].href = location.href;
app.config(function($routeProvider, $locationProvider) {
    $locationProvider.html5Mode(true).hashPrefix('!');
    $routeProvider
    .when("/", {
        templateUrl : "template/main.html",
        controller : "mainController"
    })
    .when("/red", {
        templateUrl : "template/red.html",
        controller : "redController"
    })
    .when("/green", {
        templateUrl : "template/green.html",
        controller : "greenController"
    })
    .when("/blue", {
        templateUrl : "template/blue.html",
        controller : "blueController"
    });
});

app.controller("mainController", function ($scope) {
    $scope.msg = "Main Page";
});

app.controller("redController", function ($scope) {
    $scope.msg = "Red Page";
});

app.controller("greenController", function ($scope) {
    $scope.msg = "Green Page";
});

app.controller("blueController", function ($scope) {
    $scope.msg = "Blue Page";
});

页面是index.html,red.html,green.html,blue.html,main.html

.htaccess代码

<ifModule mod_rewrite.c>
RewriteEngine on
# Don't rewrite files or directories
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule ^ angular/7/index.html [L]
</ifModule>

1 个答案:

答案 0 :(得分:1)

您需要进行网址重写,以便以/ angular / 7开头并且不是文件或目录的任何网址都会重写为/wamp/www/angular/7/index.html

搜索[your server software] SPA (single page app) rewrite。如果使用Apache,可以使用.htaccess文件完成,并且需要启用mod-rewrite。