0

I'm working on a NodeJS project including some AngularJS for routing management and I can't find out how to solve my current problem : I'm trying to check if a chosen HTML file exists before routing it. I've tried lots of solutions but for the moment, nothing seems to work. Here is my code :

    var app = angular.module("domhanWebSite", ["ngRoute"]);

    app.config(function($routeProvider, $locationProvider) {
        $locationProvider.html5Mode(false).hashPrefix('!');

        //routing management
        $routeProvider
        .when("/", {
          templateUrl : "pages/home.html"
        })
        .when("/404_not_found", {
            templateUrl : "pages/404_not_found.html"
        })
        .when("/encyclopedie/personnages/:character_html", {
            //here verification is missing
            templateUrl : function (url_attr) {
                return "pages/encyclopedia/characters/"+url_attr.character_html;
            }
        })
        .otherwise( {
          redirectTo: "/404_not_found"
        });
    });

For the third "when", I would like to check whether or not the HTML exists, and if it doesn't (because sometimes, the URL attribute does not correspond to anything), finally route to 404 error page. Does anyone have a brilliant solution ? =)

4
  • 1
    read this stackoverflow.com/a/3646923/4921471 Commented Nov 21, 2017 at 19:50
  • Thank you very much ! It seems to work perfectly ! Commented Nov 21, 2017 at 20:01
  • ;) give one + to the post , help to people ;) Commented Nov 21, 2017 at 20:03
  • Also look at how $templateCache works. No request is made for template if it is already in that cache Commented Nov 21, 2017 at 20:08

1 Answer 1

3

Finally, the solution was found thanks to this topic proposed in comments:

.when("/encyclopedie/personnages/:character_html", {
        templateUrl : function (url_attr) {
          var page = "pages/encyclopedia/characters/"+url_attr.character_html;
          if (UrlExists(page)) {return page;}
          else {return "pages/404_not_found.html";}
        }
})

With UrlExists function:

function UrlExists(url) {
    var http = new XMLHttpRequest();
    http.open('HEAD', url, false);
    http.send();
    return http.status!=404;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.