Angular HTTP inside HTTP interceptor

I need to add the required HMAC headers to the request. It shouldn't be very difficult, but I'm starting to get frustrated. What is wrong in the following code. The actual http call I am making works; I have run this call myself and it returns the required data. It doesn't work inside the interceptor.

I just want the current implementation to work before I add a whitelist or blacklist and other custom data for this interceptor. This is not a question about hmac, but with promises.

The error is in this interceptor with the entire promise line starting with $ http (...). When I remove this block and use it as is (minus the fulfillment of promises) it works fine. As soon as I uncomment the line, it gets stuck in a loop and chrome crashes. Everywhere I've read it says it's done this way, but it clearly doesn't work.

function requestInterceptor(config){
  var $http = $injector.get('$http');
  var deferred = $q.defer();

  $http.get(hmacApiEndpoint, {cache: true}).then(function(data){
    console.log('HMAC - Success', data)
    deferred.resolve(config)
  }, function(config){
    console.log('HMAC - Error', config)
    deferred.resolve(config)
  })

  return deferred.promise;
}

return {
  request: requestInterceptor
};

      

Does this have to do with the fact that the angular $ http promise is a different implementation than "$ q"?

+3


source to share


1 answer


It doesn't look like you are actually fixing config

with your newly acquired HMAC.

Also, you need to protect against your requestInterceptor

call interception in order to receive the HMAC, which will result in an endless loop.



And finally, you don't need it here deferred

- just return the promise created $http

(or $http.then()

):

function requestInterceptor(config){
  var $http = $injector.get('$http');

  // just return, if this is a call to get HMAC
  if (config.url === hmacApiEndpoint) return config;

  return $http.get(hmacApiEndpoint, {cache: true})
    .then(function(response){
      console.log('HMAC - Success', response.data)

      // not sure where the HMAC needs to go
      config.headers.Authorization = response.data;
      return config;
    })
    .catch(function(){
       return $q.reject("failed to obtain HMAC");
    });
}

return {
  request: requestInterceptor
};

      

+5


source







All Articles