Search code examples
angularjshttp-headersauthorizationrequest-headersangular-http-interceptors

Angular JS - add a custom header to all GET/POST requests


I'm trying to use an interceptor to add an 'Authorization' header to all my GET/POST requests. Here is the interceptor:

myApp.factory('httpRequestInterceptor', ['$rootScope', function ($rootScope) {
  return {
    request: function ($config) {
        $config.headers['Authorization'] = 'Basic ' + $rootScope.apiKey;
        return $config;
    }
  };
}]);

The interceptor is being used in the main module as follows in the myApp.config part:

$httpProvider.interceptors.push('httpRequestInterceptor');

For some reason I can't see the Authorization header in the network tab(I'm using Chrome) and it's not getting to the server and I don't get any errors. The GET/POST request in my application are to a remote server that is NOT in my domain.

Any idea what am I doing wrong here?

Solution: I found the problem, it was on the server side - apparently if I set the Access-Control-Allow-Headers in the response to * it doesn't work but if I specify the headers literally it works just fine.


Solution

  • the problem was on the server side - apparently setting the Access-Control-Allow-Headers in the response to * didn't work but specifying the headers literally to what i needed(Access-Control-Allow-Headers: Authorization) works just fine.