2016-02-29 37 views
1

我需要攔截http請求以添加基址(域url)到http請求並添加access_token以進行身份​​驗證(基於標記),模板域名與其他域名不同,但我的問題是,我無法識別請求是模板還是其他API(數據)。我的代碼是:

.config(["$httpProvider", function($httpProvider) { 

     $httpProvider.defaults.useXDomain = true; 
     delete $httpProvider.defaults.headers.common["X-Requested-With"]; 

     $httpProvider.interceptors.push("httpMiddleware"); 
    } 
]).factory("httpMiddleware", [ 
    function() { 
     return { 
      request: function (config) { 
       // Need to recognise request is for html template or rest api 
       var baseUrl = "http://localhost:9926/Api/"; 
       config.url = baseUrl + config.url; 
       return config; 
      } 
     }; 
    } 
]);; 

回答

0

您可以在請求的URL中檢查.html字符串。

request: function (config) { 
    // Check whether the requested url contains .html 
    if(config.url.contains('.html')) 
    { 
     // request for html templates 
    } 
    else{ 
     // request for REST api 
     // you can also do check for string API in the request url to verify that the request is to our api 
    } 
    var baseUrl = "http://localhost:9926/Api/"; 
    config.url = baseUrl + config.url; 
    return config; 
} 
0

有許多方法來驗證請求,諸如檢查,如果一個請求具有一些API特定的報頭,檢查是否URI具有如Abhilash提到模板路徑在它或檢查URI擴展

下面是示例代碼:

.config(["$httpProvider", function($httpProvider) { 

     $httpProvider.defaults.useXDomain = true; 
     delete $httpProvider.defaults.headers.common["X-Requested-With"]; 

     $httpProvider.interceptors.push("httpMiddleware"); 
    } 
]).factory("httpMiddleware", [ 
    function() { 
     return { 
      request: function (config) { 
       // Need to recognise request is for html template or rest api 
        if(config.headers['someAttr'] == valueToCheck){ 
        // or if(config.url.contains('/path/template')){ 
        // or if(config.url.contains('.html')){ 
        var baseUrl = "http://localhost:9926/Api/"; 
        config.url = baseUrl + config.url; 
       } 
       return config; 
      } 
     }; 
    } 
]);;