簡體   English   中英

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

[英]Check if HTML file exists before routing [Angular JS/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"
        });
    });

對於第三個“何時”,我想檢查HTML是否存在,如果不存在(因為有時URL屬性不對應任何內容),最后轉到404錯誤頁面。 有誰有一個出色的解決方案? =)

最后,由於在注釋中提出了該主題 ,因此找到了解決方案:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM