The $ http interceptor calls an infinite loop

I am building an AngularJs app that runs with a custom API that requires a valid authorization token, if not, my API returns HTTP status code 4O1.

Thus, I am using an http interceptor, which is designed to request a new token before repeating the previous request.

    app.factory('httpResponseErrorInterceptor', ['$q', '$injector', function($q, $injector, $http) {
    return {
        'responseError': function(response) {
            if (response.status === 401) {
                // should retry
                let deferred = $q.defer();
                let $http = $injector.get('$http');
                $.ajax({
                    url        : PUBLIC_API_URI,
                    type       : 'HEAD',
                    beforeSend : function(request) {
                        request.setRequestHeader('Authorization', api_access_key);
                    },
                    success    : function(result, status, xhr) {
                        console.log("error -> ok : should retry");
                        deferred.resolve(xhr.getResponseHeader('Authorization'));
                    },
                    error      : function(xhr, status, error) {
                        console.log("error -> bad : should give up");
                        deferred.resolve(null);
                    }
                });
                console.log(deferred.promise);
                if(deferred.promise == null)
                    return $q.reject(response);
                response.config['Authorization'] = api_access_key = deferred.promise;
                return $http(response.config);
            }

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

      

I used JQuery.ajax in my interceptor because I figured out that using $ http causes an infinite loop when the token refresh request resulted in an error. But it still causes an infinite loop on error: original-request -> renewal request ...

+3


source to share


1 answer


I don't see the complete error log, but I think the problem might be with the introduction of the service $http

(which still exists even if you use $ .ajax) inside the http interceptor. this will cause a circular dependency because angular will run into an infinite loop trying to resolve both the dependency $http

and its interceptor.

see my previous answer here



if you need to make an ajax call try injecting the service "as needed"

angular.module('myApp').factory('interceptor', function($injector){

  return {
      'responseError': function(response) {
         var http = $injector.get('$http');
         http.get..
       }
  }

});

      

+2


source







All Articles