To get rid of #! in angularjs ngRoute

I work with Angularjs ngRoute for SPA with Node.js as my backend, I have 3 pages on my website:

  • localhost:8000/#!/
  • localhost:8000/#!/red
  • localhost:8000/#!/green

By googling, I found a way to get rid of /**#!**/, and it worked fine only when the user has no intention of pressing F5 to reload the page. If it reloads, the structure of my page is deteriorating. What I mean: if the user pressed F5 when he / she is on the page red.html, then it is displayed only red.htmlinstead of entering the contents red.htmlinto ng-View . Thats the nature of nodejs get the request. Are there any ways to get rid of this problem?

index.html

<body ng-app="myApp">
  <p><a href="/">Main</a></p>
  <a href="/red">Red</a>
  <a href="/green">Green</a>

  <ng-view></ng-view>

  <script>
    var app = angular.module("myApp", ["ngRoute"]);
    app.config(function($routeProvider, $locationProvider) {
      $routeProvider
        .when("/", {
          templateUrl: "/main"
        })
        .when("/red", {
          templateUrl: "/red"
        })
        .when("/green", {
          templateUrl: "/green"
        })

      $locationProvider.html5Mode(true);
    });

  </script>
</body>
+4
2

node.js express, ? , index.html , :

//resources 
app.use("/js", express.static(__dirname + "/js"));
app.use("/img", express.static(__dirname + "/img"));
app.use("/css", express.static(__dirname + "/css"));

//different path for your partials to avoid route conflicts
app.use("/partials", express.static(__dirname + "/partials"));

//view routes
app.get('/*', function(req, res){
    res.sendFile(__dirname + '/index.html');
});

, :

  • localhost:8000/
  • localhost:8000/red
  • localhost:8000/green

index.html. , $routeProvider , index.html .

, :

var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider, $locationProvider) {
  $routeProvider
    .when("/", {
      templateUrl: "/partials/main.html"
    })
    .when("/red", {
      templateUrl: "/partials/red.html"
    })
    .when("/green", {
      templateUrl: "/partials/green.html"
    })

  $locationProvider.html5Mode(true);
});
+3

, html5- F5, red.html, index.html. , angular URL-, .

EDIT: :

  • ( F5 ) http://localhost:8000, index.html .
  • ( F5 ) http://localhost:8000/red, index.html .

Bonus:

(, css, html-) , http://localhost:8000/static/ , URL-

0

Source: https://habr.com/ru/post/1679552/


All Articles