$httpProvider 拦截器没有拦截我的 API 调用

$httpProvider interceptor not intercepting my API calls

我有一个 angular 应用程序向 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 header。问题出现是因为我调用的 REST API 使用了 Spring-CORS 库,该库在 401 和 403 响应中不包含 CORS headers。

这是一个 cross-site 域问题,因为尽管您使用本地主机,但您的 API 调用域与 UI 的(端口 8080 和 8081)不同,请阅读此内容文章了解更多信息。您需要在您的网络服务器中添加此 header:

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

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