javascript - Angularjs $http 拦截器 - 无法生成对 requestError 的调用

标签 javascript angularjs angular-http-interceptors

我使用 $http 拦截器来捕获 ajax 提交后的所有事件。由于某种原因,我无法抛出 requestError。我已经设置了一个测试应用来尝试调用 requestError,但到目前为止我只能获得多个 responseErrors

来自 angularjs 文档:

requestError: interceptor gets called when a previous interceptor threw an error or resolved with a rejection.

这是我的测试代码。

        .factory('httpInterceptor',['$q',function(q){

            var interceptor = {};

            var uniqueId = function uniqueId() {
                return new Date().getTime().toString(16) + '.' + (Math.round(Math.random() * 100000)).toString(16);
            };

            interceptor.request = function(config){
                config.id = uniqueId();
                console.log('request ',config.id,config);
                return config;
            };

            interceptor.response = function(response){
                console.log('response',response);
                return response;                    
            };

            interceptor.requestError = function(config){
                console.log('requestError ',config.id,config);
                return q.reject(config);
            };

            interceptor.responseError = function(response){
                console.log('responseError ',response.config.id,response);
                return q.reject(response);                    
            };

            return interceptor;

        }])

        .config(['$httpProvider',function($httpProvider) {
            $httpProvider.interceptors.push('httpInterceptor');
        }])

        .controller('MainCtrl',['$http',function($http){

            var mainCtrl = this;

            mainCtrl.method = null;
            mainCtrl.url = null;

            var testHttp = function testHttp() {

                $http({method:mainCtrl.method,url:mainCtrl.url}).then(
                        (response)=>{console.log('ok',response);},
                        (response)=>{console.log('reject',response);}
                );
            };

            //api
            mainCtrl.testHttp = testHttp;

        }])

我尝试了多种创建 http 错误的方法,每次都只调用 responseError 。我尝试过的事情:

  • 让服务器为每个请求返回不同类型的错误,例如400500
  • 让服务器随机 sleep 次,以使稍后的请求在较早的请求之前响应错误。相同的资源,相同的服务器响应。
  • 通过请求不存在的资源生成 404 错误。
  • 断开与互联网的连接 (responseError -1)。

类似问题

1)这个问题似乎有答案: When do functions request, requestError, response, responseError get invoked when intercepting HTTP request and response?

关键段落是:

A key point is that any of the above methods can return either an "normal" object/primitive or a promise that will resolve with an appropriate value. In the latter case, the next interceptor in the queue will wait until the returned promise is resolved or rejected.

但我认为我正在按照它的规定去做,即服务器随机 sleep 但没有运气。我收到请求中的 reponseErrors 乱序,即服务器响应后。

2)大约一年前有人问过类似的问题:Angular and Jasmine: How to test requestError / rejection in HTTP interceptor?

不幸的是,它只提供了拦截器的解释。它没有回答我的问题。

我已经在 ChromeFirefox 中进行了测试。希望您能理解,我已经尽力找到解决方案,但目前还没有找到解决方案。

最佳答案

发生这种情况是因为请求在任何时候都没有被拒绝。应该使用like that :

app.factory('interceptor1', ['$q', function ($q) {
  return {
    request: function (config) {
      console.log('request', config);
      if (config.url === 'restricted')
        return $q.reject({ error: 'restricted', config: config });
    }
  };
}]);

app.factory('interceptor2', ['$q', function ($q) {
  return {
    requestError: function (rejection) {
      console.log('requestError', rejection);      
      if (rejection.error === 'restricted')
        return angular.extend(rejection.config, { url: 'allowed' });

      return $q.reject(rejection);
    }
  };
}]);

app.config(['$httpProvider',function($httpProvider) {
  $httpProvider.interceptors.push('interceptor1');
  $httpProvider.interceptors.push('interceptor2');
}]);

请注意,拦截器应该在堆栈中工作(从 $http 请求中的 transform* Hook 开始),因此请求不能在一个时间内被拒绝和恢复。单个拦截器。

关于javascript - Angularjs $http 拦截器 - 无法生成对 requestError 的调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39372692/

相关文章:

javascript - 使用 JavaScript 发出跨站点请求的最佳方式?

javascript - 如何检查Web应用程序浏览器中是否安装了dymo标签打印机驱动程序?

javascript - 根据 promise 的结果将列添加到动态 ng-table

java - 注销后无法清除访问 token

javascript - 为什么我的 Angular 不能正常工作?

angularjs - 在多个 http 调用中处理 Spinner

angular - 如何在拦截器Angular 8中传递用户ID

javascript - 将 div 设置为固定,直到它与其他元素接触并成为绝对元素。向上滚动时不会恢复为固定状态

javascript - 正确附加嵌入播放器的问题

angularjs - 在Grails应用中使用Spring Security Rest插件调用登录时出现401未经授权的错误