Mr Smith Mr Smith - 4 months ago 113
AngularJS Question

How to remove authorization header from request

I'm using MEAN Stack User Registration and Login Example & Tutorial as the base for my app. It adds an auth header to every request in the run function:

$http.defaults.headers.common['Authorization'] = 'Bearer ' + $window.jwtToken;


I want to upload images to Cloudinary but I'm getting this error:


XMLHttpRequest cannot load https://api.cloudinary.com/v1_1/xxxx/upload. Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.


How can I remove this header specifically for requests to Cloudinary?

Answer

You will require an interceptor that checks for the url of the request and clears the header if it matches. alternatively you can use the $http config parameter.

Using the parameter:

$http.post('https://api.cloudinary.com/v1_1/' + someId + '/upload', data, { headers: {} });

Using an interceptor:

.factory('cloudinaryInterceptor', function() {
 return {
  request: function(config){
   var authHeader = config.headers('authorization');
   //Check for the host
   var regex = /api.cloudinary.com/i;
   if(regex.test(config.url))
    //Detach the header
    delete config.headers.authorization;
   return config;
  }
 }
});

Remember to push the interceptor in the config phase

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