在路由之前检查HTML文件是否存在[Angular JS / Node JS]

时间:2017-11-21 19:49:30

标签: javascript angularjs node.js

我正在开发一个NodeJS项目,包括一些用于路由管理的AngularJS,我无法找到解决当前问题的方法:我正在尝试检查选择的HTML文件是否存在,然后再进行路由。我已经尝试了很多解决方案,但目前看来似乎没有任何效果。这是我的代码:

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

对于第三个“when”,我想检查HTML是否存在,如果不存在(因为有时URL属性不对应),最后路由到404错误页面。有人有一个出色的解决方案吗? =)

1 个答案:

答案 0 :(得分:2)

最后,由于评论中提出了this topic而找到了解决方案:

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

具有UrlExists功能:

function UrlExists(url) {
    var http = new XMLHttpRequest();
    http.open('HEAD', url, false);
    http.send();
    return http.status!=404;
}
相关问题