2015-09-24 165 views
1

我有一個角度應用程序向API服務發出異步請求。由於很多資源在API服務上受到保護,因此我需要攔截對服務進行的HTTP請求。但據我所見,我定義的攔截器只攔截頁面加載請求。

這裏是實驗我已經拿出來說明我的問題:

myApp = angular.module('myApp', []); 

myApp.config(['$httpProvider', function($httpProvider) { 
    $httpProvider.interceptors.push(function() { 
     return { 
      response: function(response) { 
       console.log(response); 
       return response; 
      } 
     }; 
    }); 
}); 

我能看到的是,攔截器攔截除API調用,你可以從看到所有呼叫顯示控制檯輸出的附加屏幕截圖。

從下面的屏幕截圖中可以看到,控制檯輸出包含部分模板加載時記錄的響應,但不包括向API服務發出GET請求時的響應。

爲什麼會發生這種情況?

screenshot showing dev tools with the console output

更新

我已經改變了我的設置,包括請求和響應的所有可能的組合現在:

$httpProvider.interceptors.push(function() { 
    return { 
     request: function(request) { 
      console.log(request); 
      return request; 
     }, 
     requestError: function(request) { 
      console.log(request); 
      return config; 
     }, 
     response: function(response) { 
      console.log(response); 
      return response; 
     }, 
     responseError: function(response) { 
      console.log(response); 
      return response; 
     } 
    }; 
}); 

現在攔截器攔截的消息,但古怪顯示的狀態被捕獲的responseError爲:

status: -1 

雖然它顯然是一個401

更新2

事實證明,甚至401響應所需要的CORS標頭被添加到它。自從調用使用Spring-CORS庫的REST API以來,問題就出現了,它在401和403響應中不包含CORS頭文件。

+0

顯然,從錯誤消息,API調用並沒有因跨域請求成功。如果您打算捕獲該數據,則在攔截器中使用'responseError' –

回答

0

這是一個跨站點域問題,因爲儘管您使用本地主機的API調用域與UI的不同(端口8080 & 8081),請閱讀本文以獲取更多信息。您需要在您的Web服務器添加此標題:

Access-Control-Allow-Origin: http://foo.example 

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

+0

如果仔細觀察,則響應是來自服務器的401。我不認爲這將與一個CORS標題。 – shyam

+0

不知道還有什麼要告訴你,看到這個計算器獲取更多信息。 http://stackoverflow.com/questions/17224937/origin-is-not-allowed-by-access-control-allow-origin-in-angularjs-and-asp-net-mv – cullimorer