Angular set headers for specific endpoints angular 1

141 Views Asked by At

I have looked round but couldn't find something that works for me. I have 2 endpoints, one for a backend I have access to and the other for an external service.

in my .run I have an interceptor that adds this header to every request that is made to my server $http.defaults.headers.common['Authorization'] = 'JWT' + ' ' token';

Service for the external api.

 service('CorsRequest', function ($http) {

            var baseUrl = 'https://min-api.cryptocompare.com/';

            this.get = function (endpoint) {
                return $http.get(baseUrl + endpoint, { headers: {"Content-Type": 'text/plain'}});

            }

            this.post = function (endpoint, postData) {
                return $http.post(baseUrl + endpoint, postData);
            }
        })

the 2nd endpoint returns a preflight error when a request is made to that api because this Authorization header is added to it.

How do I check that if the request is going to my server, add the Authorization header and if not ignore.

1

There are 1 best solutions below

0
On BEST ANSWER

Here's how I fixed with with a http interceptor as Slava suggested.

created a factory for it and used the injector to get the service I created to use it with.

  .factory('ApiInterceptor', function($localStorage, $injector){

    console.log('here')
    return {
       request: function(config) {

      var UserService = $injector.get('UserService');

      if(config.url.indexOf(BASE_URL) > -1) {
        config.headers['Authorization'] = 'JWT' + ' ' + UserService.getCurrentUserToken() ;

      }
      // console.log(config)
      return config;
    },
      response: function(response) {
          // console.log(response.data);
          return response;
        }
    }

})

then added the config.

.config(function($httpProvider) {       
    $httpProvider.interceptors.push('ApiInterceptor');
  })