AngularJS routing 404 error with HTML5 mode

2019-01-03 07:16发布

I just got started with angular js , i tried routing and worked pretty well .The problem is when i refresh the page it is showing 404 error since it is checking in my actual directory rather than checking in routes.

here is the complete code

<!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>

here are the browser outputs

output

this is when i refresh

error

please provide me with some solution.

3条回答
欢心
2楼-- · 2019-01-03 07:38

The problem is that you are not assigning the variable,$routeProvider to your controller, this causes the controller not to be able to access the variable $ routeParams

try it

 /*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";
    });

UPDATE

I think you can not use a route version with a lower version of angulajs please change a upper version of angularjs for example

/* <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>

查看更多
forever°为你锁心
3楼-- · 2019-01-03 07:43

HTML5 mode requires URL rewriting.

From the Docs:

HTML5 Mode

Server side

Using this mode requires URL rewriting on server side, basically you have to rewrite all your links to entry point of your application (e.g. index.html). Requiring a <base> tag is also important for this case, as it allows AngularJS to differentiate between the part of the url that is the application base and the path that should be handled by the application.

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

For NodeJS and 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;

For IIS on Windows

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

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

For apache

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

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

For more information

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

查看更多
一纸荒年 Trace。
4楼-- · 2019-01-03 07:52

I had the same problem using http-server as my local webserver, its a known issue with html5 and detailed in the angular-ui/ui-router FAQ.

I switched to Nginx (install via apt-get) with the following /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;
    }

 }

To start/stop/reload after changes;

sudo service nginx <start|stop|status>

The FAQ also covers Apache/Express/asp.NET

查看更多
登录 后发表回答