How to set HTTP headers in AngularJS using $http service?
When performing an HTTP transaction in any application, there are times when you will need to add/read headers to/from requests and responses respectively. Most common use case is to add authentication data to the headers while making a request to access any protected service. In this post, I’ll tell you how to set HTTP headers in AngularJS using $http service.
There is a built-in angular service to make any HTTP requests, named $http. Use this service to make GET, POST, DELETE, PUT, PATCH requests to a service 9tncbhm.
If you would like to add some headers to be sent with every request in your application, consider configuring the $httpProvider or $http module as shown below.
The $http service will automatically add certain HTTP headers to all requests. These defaults can be fully configured by accessing the configuration object,$httpProvider.defaults.headers
1 2 3 4 5 |
// Example: set a header for every POST request, define this in your app’s configuration: $httpProvider.defaults.headers.post[‘Content-Type’] = ‘application/json; charset=utf-8’; // Example: set a header using $http directly: this header will be used in all requests: $http.defaults.headers.common[‘Content-Type’] = ‘application/json; charset=utf-8’; |
Also, if you have special cases where just a single or few HTTP requests needs some extra headers, use the following options:
1 2 3 4 5 6 7 8 9 10 11 12 |
$http({ method: ‘POST’, url: ‘http://my-endpoint/login’, headers: {‘Authorization’: ‘token-data’} }); // when using the post utility function $http.post(‘http://my-endpoint/login’, { headers: {‘Authorization’: ‘token-data’} } ); |
