AngularJS 使用 HTML5 模式路由 404 错误

IT技术 javascript angularjs http-status-code-404 ngroute angularjs-ng-route
2021-02-06 03:56:07

我刚开始使用 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个回答

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 模式下重写 AngularJS 应用程序的 URL?

对于apache

RewriteEngine On RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR] 
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
RewriteRule ^ - [L]
RewriteRule ^

请参阅如何在 apache htaccess 中为 angularjs 应用程序重写 url

想要查询更多的信息

文章:AngularJS - 在 NodeJS 和 IIS 中启用 HTML5 模式页面刷新而不会出现 404 错误

我将 .htaccess 更改为重定向到 index.html。现在它工作正常!
2021-03-16 03:56:07
完成!👍🏻 RewriteEngine On RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR] RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d RewriteRule ^ - [L] RewriteRule ^ /index.html 这是我使用的代码在.htaccess中
2021-03-29 03:56:07

我在使用 http-server 作为我的本地网络服务器时遇到了同样的问题,这是 html5 的一个已知问题,在angular-ui/ui-router FAQ 中有详细说明

我使用以下命令切换到 Nginx(通过 apt-get 安装) /etc/nginx/sites-enabled/default

server {
    listen 80 default_server;
    listen [::]:80 default_server;

    #root /var/www/html;

    root /home/conor/workspace/code_institute/route_test;

    # Add index.php to the list if you are using PHP
    index index.html index.htm index.nginx-debian.html;

    #server_name _;
    server_name localhost;

    location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        #try_files $uri $uri/ =404;
        try_files $uri $uri/ /index.html;
    }

 }

更改后启动/停止/重新加载;

sudo service nginx <start|stop|status>

FAQ 还包括 Apache/Express/asp.NET

问题是您没有将变量 $routeProvider 分配给您的控制器,这会导致控制器无法访问变量 $ routeParams

试试看

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

      $scope.msg = "this is blue";
    });
    app.controller("green_control", function($scope) {
      $scope.msg = "this is green";
    });*/
 app.controller("blue_control", function($scope,$routeParams) {
     console.log( $routeParams.term_user);
      $scope.msg = "this is blue";
    });
    app.controller("green_control", function($scope,$routeParams) {
      $scope.msg = "this is green";
    });

更新

我认为您不能使用较低版本的 angulajs 的路由版本,例如请更改较高版本的 angularjs

/* <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.6.4/angular.min.js"></script>

<!DOCTYPE html>
<html>


<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.4.8/angular-route.js"></script>

<body ng-app="app">

  <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("app", ['ngRoute']);

    app.config(function($routeProvider) {
      $routeProvider
        .when("/blue/:name?", {
          templateUrl: "blue.html",
          controller: "blue_control"
        })

        .when("/green", {
          templateUrl: "green.html",
          controller: "green_control"
        })

      

    });
    app.controller("blue_control", ['MyFirstController',function($scope, $routeParams) {
      $scope.msg = "this is blue";
    }]);
    app.controller("green_control", ['MyFirstController2',function($scope, $routeParams) {
      $scope.msg = "this is green";
    }]);
  </script>


</body>

</html>