为了账号安全,请及时绑定邮箱和手机立即绑定

HTML5模式下的AngularJS路由404错误

HTML5模式下的AngularJS路由404错误

FFIVE 2019-09-27 15:56:36
我刚开始使用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>
查看完整描述

3 回答

?
猛跑小猪

TA贡献1858条经验 获得超8个赞

HTML5模式需要URL重写。

从文档中:


HTML5模式

服务器端

使用此模式需要在服务器端重写URL,基本上,您必须重写所有指向应用程序入口点的链接(例如index.html)。<base>在这种情况下,要求标签也很重要,因为它使AngularJS能够区分作为应用程序基础的url部分和应由应用程序处理的路径。


— AngularJS开发人员指南-使用$ location(HTML5模式服务器端)


对于NodeJS和ExpressJS

var express = require('express');

var path = require('path');

var router = express.Router();


// serve angular front end files from root path

router.use('/', express.static('app', { redirect: false }));


// rewrite virtual urls to angular app to enable refreshing of internal pages

router.get('*', function (req, res, next) {

    res.sendFile(path.resolve('app/index.html'));

});


module.exports = router;

对于Windows上的IIS

<rewrite>

  <rules>

    <rule name="AngularJS" stopProcessing="true">

      <match url=".*" />

      <conditions logicalGrouping="MatchAll">

        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />

        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />

      </conditions>

      <action type="Rewrite" url="/" />

    </rule>

  </rules>

</rewrite>

请参阅,如何配置IIS以在HTML5模式下用URL重写AngularJS应用程序?


对于阿帕奇

RewriteEngine On RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR] 

RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d

RewriteRule ^ - [L]

RewriteRule ^


查看完整回答
反对 回复 2019-09-27
  • 3 回答
  • 0 关注
  • 1179 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信