【问题标题】:AngularJS routing 404 error with HTML5 modeAngularJS在HTML5模式下路由404错误
【发布时间】:2017-10-31 11:20:59
【问题描述】:

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

这里是浏览器输出

这是我刷新的时候

请给我一些解决方案。

【问题讨论】:

标签: javascript angularjs http-status-code-404 ngroute angularjs-ng-route


【解决方案1】:

HTML5 模式需要 URL 重写。

来自文档:

HTML5 模式

服务器端

使用此模式需要在服务器端重写 URL,基本上你必须重写所有指向应用程序入口点的链接(例如 index.html)。对于这种情况,要求&lt;base&gt; 标记也很重要,因为它允许 AngularJS 区分作为应用程序基础的 url 部分和应由应用程序处理的路径。

— AngularJS Developer Guide - Using $location (HTML5 Mode Server Side)

对于 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>

见,How do I configure IIS for URL Rewriting an AngularJS application in HTML5 mode?

对于阿帕奇

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

见,How to rewrite url in apache htaccess for angularjs app

更多信息

文章:AngularJS - Enable HTML5 Mode Page Refresh Without 404 Errors in NodeJS and IIS.

【讨论】:

  • 我将 .htaccess 更改为重定向到 index.html。现在它工作正常!
  • 完成!?? RewriteEngine On RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR] RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d RewriteRule ^ - [L] RewriteRule ^ /index. html 这是我在 .htaccess 中使用的代码
【解决方案2】:

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

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

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>

常见问题解答还包括 Apache/Express/asp.NET

【讨论】:

    【解决方案3】:

    问题是您没有将变量 $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>

    【讨论】:

      猜你喜欢
      • 2014-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-10
      • 2018-04-10
      • 2018-10-21
      • 2014-11-03
      • 2018-08-25
      相关资源
      最近更新 更多