【问题标题】:$httpProvider interceptor not intercepting my API calls$httpProvider 拦截器没有拦截我的 API 调用
【发布时间】:2015-09-29 18:24:47
【问题描述】:

我有一个 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 标头添加到其中。问题出现是因为我调用的 REST API 使用了 Spring-CORS 库,该库在 401 和 403 响应中不包含 CORS 标头。

【问题讨论】:

  • 很明显,从报错信息来看,API调用由于跨域请求没有成功。如果您打算捕获它,请在拦截器中使用responseError

标签: angularjs xmlhttprequest


【解决方案1】:

这是一个跨站点域问题,因为尽管您使用 localhost,但您的 API 调用域与 UI 不同(端口 8080 和 8081),请阅读本文以获取更多信息。您需要在您的网络服务器中添加此标头:

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

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

【讨论】:

  • 如果您仔细观察,响应是来自服务器的 401。我不认为这会带有 CORS 标头。
  • 不确定还能告诉您什么,请参阅此 stackoverflow 了解更多信息。 stackoverflow.com/questions/17224937/…
猜你喜欢
  • 1970-01-01
  • 2016-10-31
  • 2014-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-22
相关资源
最近更新 更多