Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS $http custom header for all requests

Tags:

http

angularjs

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

like image 454
alexsc Avatar asked Apr 29 '15 13:04

alexsc


2 Answers

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');  });
like image 78
boindiil Avatar answered Sep 19 '22 14:09

boindiil


A simpler solution could be to use Angular's run block:

app.run(['$http', function ($http) {     $http.defaults.headers.common['Authorization'] = 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==';     $http.defaults.headers.common['Accept'] = 'application/json;odata=verbose'; }]); 

Note: This solution allows you to pass the static value only one time since the run block executes only once.

like image 41
Shashank Agrawal Avatar answered Sep 18 '22 14:09

Shashank Agrawal