anjularjs中http请求添加头部请求信息

在AngularJs中有三种方式可以设置请求头信息:

1、在httphttp服务的在服务端发送请求时,也就是调用http()方法时,在config对象中设置请求头信息:事例如下:

    $http.post('/somePath' , someData , {
        headers : {'Authorization' : authToken}
    }).success(function(data, status, headers, config) {
        //...
    }).error(function(data, status, headers, config ) {
        //...
    });
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

这种方法的好处就是针对不同路径的请求,可以个性化配置请求头部,缺点就是,不同路径请求都需要单独配置。

2、第二种设置请求头信息的方式就是在$httpProvider.defaults.headers属性上直接配置。事例如下:

ngular.module('app', [])
.config(function($httpProvider) {
    $httpProvider.defaults.headers.common = { 'My-Header' : 'value' }
})
  • 1
  • 2
  • 3
  • 4
  • 5

$httpProvider.defaults.headers有不同的属性,如common、get、post、put等。因此可以在不同的http请求上面添加不同的头信息,common是指所有的请求方式。

这种方式添加请求头信息的优势就是可以给不同请求方式添加相同的请求头信息,缺点就是不能够为某些请求path添加个性化头信息。

3、第三种设置请求头信息的地方是$httpProvider.interceptors。也就是为请求或相应注册一个拦截器。使用这这方式我们首先需要定义一个服务。

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){
            // ...
        }
    };
})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

然后把上面定义的服务注册到$httpProvider.interceptors中。

.config(function($httpProvider){
    $httpProvider.interceptors.push('authInterceptor');
})
  • 1
  • 2
  • 3
  • 4

这样,对于每次请求,不论是get还是post、put。我们都会在请求头信息中加入authorization属性。这种方式在处理验权、授权方面很有用的。但是确定就是不能够为特定的请求方式添加请求头信息。

上面总共有三种方式设置头信息,选择那种方式可以根据自己的需求。

猜你喜欢

转载自blog.csdn.net/p3118601/article/details/80612031
今日推荐