我有一個角度應用程序向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請求時的響應。
爲什麼會發生這種情況?
更新
我已經改變了我的設置,包括請求和響應的所有可能的組合現在:
$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頭文件。
顯然,從錯誤消息,API調用並沒有因跨域請求成功。如果您打算捕獲該數據,則在攔截器中使用'responseError' –