Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting angularjs $http headers globally

I have a webapp with multiple controllers. I'm setting the defaults headers of the $http service in a callback in one of my controllers (via http.defaults.headers.common['headername']). However, those headers do not get set in subsequent calls from other controllers. Do I have to set them for each controller I have or is one time enough?

like image 340
flower_green Avatar asked Nov 25 '14 19:11

flower_green


People also ask

How do you modify the $HTTP request default Behaviour?

To add or overwrite these defaults, simply add or remove a property from these configuration objects. To add headers for an HTTP method other than POST or PUT, simply add a new object with the lowercased HTTP method name as the key, e.g. $httpProvider. defaults. headers.

What is $HTTP in AngularJS?

$http is an AngularJS service for reading data from remote servers.

How do we pass data and get data using HTTP in angular?

Use the HttpClient.get() method to fetch data from a server. The asynchronous method sends an HTTP request, and returns an Observable that emits the requested data when the response is received. The return type varies based on the observe and responseType values that you pass to the call.


1 Answers

You should use one of two methods:

Set $http.defaults.headers in run block e.g.

 module.run(function($http) {
  $http.defaults.headers.common.Authorization = 'Basic Token';
});

Use interceptor

var interceptor = function() {
  return {
    'request': function(config) {
      config.headers['Authorization'] = 'Basic Token';
     }
  }
};

angular.module('app', [])
  .config(function ($httpProvider) {
    $httpProvider.interceptors.push(interceptor);
});
like image 133
Gleb Vinnikov Avatar answered Sep 22 '22 14:09

Gleb Vinnikov