Original: http://blog.csdn.net/magiclr/article/details/49643277
There are three ways to set the request header information in Angularjs:
1, inHTTPClothingWorksOfInClothingWorksEndHairSendPleasePlease , it 's a tune- in . HTTP () method, set the request header information in the Config object:
$http.post(‘/somePath‘ , someData , { headers : {‘Authorization‘ : authToken} }).success(function(data, status, headers, config) { //... }).error(function(data, status, headers, config ) { //... });
The benefit of this approach is that requests for different paths can be configured to personalize the request header, with the disadvantage that different path requests need to be configured separately.
2, the second way to set the request header information is directly configured on the $httpprovider.defaults.headers property.
ngular.module(‘app‘, []).config(function($httpProvider) { $httpProvider.defaults.headers.common = { ‘My-Header‘ : ‘value‘ }})
$httpProvider. Defaults.headers have different properties, such as common, get, post, put, and so on. So you can add different header information to different HTTP requests, common refers to all the request methods.
The advantage of adding request header information in this way is that you can add the same request header information to different request methods, with the drawback that you cannot add personalization header information to some request path.
3. The third place to set the request header information is $httpprovider.interceptors. That is, registering an interceptor for a request or response. Using this approach, you first need to define a service.
myModule.factory(‘authInterceptor‘, function($rootScope, $cookies){ return { request: function(config){ config.headers = config.headers || {}; if($cookies.get(‘token‘)){ config.headers.authorization = ‘Bearer ‘ + $cookies.get(‘token‘); } return config; }, responseError: function(response){ // ... } };})
The service defined above is then registered in the $httpprovider.interceptors.
.config(function($httpProvider){ $httpProvider.interceptors.push(‘authInterceptor‘);})
Thus, for each request, whether it be get or post, put. We will add the authorization attribute to the request header message. This approach is useful in dealing with powers of inspection and authorization. The disadvantage is that the request header information cannot be added for a specific request method.
Different ways to set request header information