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.
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.
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' } .
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.
$http is an AngularJS service for reading data from remote servers.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With