alexsc alexsc - 5 months ago 49
AngularJS Question

AngularJS $http custom header for all requests

I was wondering if there is any way to configure all $http requests header with adding custom info. Something like config :

var config = {headers: {
'Authorization': 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==',
'Accept': 'application/json;odata=verbose'
}
};


But for all $http calls I will make in different services. I'm sure there is a solution :D.Thanks

Answer

You can create a $http interceptor to extend your header:

myapp.factory('httpRequestInterceptor', function () {
  return {
    request: function (config) {

      config.headers['Authorization'] = 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==';
      config.headers['Accept'] = 'application/json;odata=verbose';

      return config;
    }
  };
});

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