HTML5模式下的AngularJS路由404错误

我刚开始使用angular js,我尝试了路由并且工作得很好。问题是当我刷新页面时它显示404错误,因为它正在检查我的实际目录而不是在检查路由。


这是完整的代码


<!DOCTYPE html>

<html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.js"></script>


<body ng-app="myApp">


  <base href="/" />


  <a href="blue">blue</a>


  <a href="green">green</a> //blue.html and green.html are in same directory as index.html


  <p>Click on the links to load blue or green.</p>


  <div ng-view></div>


  <script>

    var app = angular.module("myApp", ["ngRoute"]);


    app.config(function($routeProvider, $locationProvider) {

      $routeProvider

        .when("/blue/:name?", {

          templateUrl: "blue.html",

          controller: "blue_control"

        })


        .when("/green", {

          templateUrl: "green.html",

          controller: "green_control"

        })


      $locationProvider.html5Mode({

        enabled: true

      });


    });

    app.controller("blue_control", function($scope) {

      $scope.msg = "this is blue";

    });

    app.controller("green_control", function($scope) {

      $scope.msg = "this is green";

    });

  </script>



</body>


</html>



FFIVE
浏览 1240回答 3
3回答

猛跑小猪

HTML5模式需要URL重写。从文档中:HTML5模式服务器端使用此模式需要在服务器端重写URL,基本上,您必须重写所有指向应用程序入口点的链接(例如index.html)。<base>在这种情况下,要求标签也很重要,因为它使AngularJS能够区分作为应用程序基础的url部分和应由应用程序处理的路径。— AngularJS开发人员指南-使用$ location(HTML5模式服务器端)对于NodeJS和ExpressJSvar express = require('express');var path = require('path');var router = express.Router();// serve angular front end files from root pathrouter.use('/', express.static('app', { redirect: false }));// rewrite virtual urls to angular app to enable refreshing of internal pagesrouter.get('*', function (req, res, next) {&nbsp; &nbsp; res.sendFile(path.resolve('app/index.html'));});module.exports = router;对于Windows上的IIS<rewrite>&nbsp; <rules>&nbsp; &nbsp; <rule name="AngularJS" stopProcessing="true">&nbsp; &nbsp; &nbsp; <match url=".*" />&nbsp; &nbsp; &nbsp; <conditions logicalGrouping="MatchAll">&nbsp; &nbsp; &nbsp; &nbsp; <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />&nbsp; &nbsp; &nbsp; &nbsp; <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />&nbsp; &nbsp; &nbsp; </conditions>&nbsp; &nbsp; &nbsp; <action type="Rewrite" url="/" />&nbsp; &nbsp; </rule>&nbsp; </rules></rewrite>请参阅,如何配置IIS以在HTML5模式下用URL重写AngularJS应用程序?对于阿帕奇RewriteEngine On RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]&nbsp;RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -dRewriteRule ^ - [L]RewriteRule ^
打开App,查看更多内容
随时随地看视频慕课网APP