Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting application wide HTTP headers in AngularJS

Is there a way to set the $httpProvider headers outside of angular.module('myApp', []).config()?

I'm getting an Auth-Token from the server after I login the user, and I need to add it as a HTTP Header to all following requests.

like image 312
lucassp Avatar asked Jan 06 '13 14:01

lucassp


People also ask

How do I set HTTP headers?

In the web site pane, double-click HTTP Response Headers in the IIS section. In the actions pane, select Add. In the Name box, type the custom HTTP header name. In the Value box, type the custom HTTP header value.

Which of the options is correct for setting headers in AngularJS HTTP POST request?

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. get = { 'My-Header' : 'value' } .

How do you pass headers in angular HTTP?

There are two ways by which we can add the headers. One, we add the HTTP Headers while making a request. The second way is to use the HTTP interceptor to intercept all the Requests and add the Headers. In both cases, we use the httpHeaders configuration option provided by angular HttpClient to add the headers.

What is $HTTP in AngularJS?

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


1 Answers

You can use default headers for angular 1.0.x:

$http.defaults.headers.common['Authentication'] = 'authentication'; 

or request interceptor for angular 1.1.x+:

myapp.factory('httpRequestInterceptor', function () {   return {     request: function (config) {        // use this to destroying other existing headers       config.headers = {'Authentication':'authentication'}        // use this to prevent destroying other existing headers       // config.headers['Authorization'] = 'authentication';        return config;     }   }; });  myapp.config(function ($httpProvider) {   $httpProvider.interceptors.push('httpRequestInterceptor'); }); 

Since factories/services are singletons, this works as long as you do not need to dynamically change your 'authentication' value after the service has been instantiated.

like image 90
Leonardo Zanivan Avatar answered Sep 20 '22 08:09

Leonardo Zanivan