angular学习笔记(二十四)-$http(2)-设置http请求头

1. angular默认的请求头:

angular学习笔记(二十四)-$http(2)-设置http请求头

其中,Accept 和 X-Requested-With是$http自带的默认配置

Accept:application/json,text/plain         接受的请求的数据类型: json 文本

X-Requested-With: XMLHttpRequest    请求是通过XMLHttpRequest对象发送的

2. 修改默认请求头:

(1) 全局修改(整个模块)

使用$httpProvider依赖

        var myApp = angular.module('MyApp',[]);

        myApp.config(function($httpProvider){

             console.log($httpProvider.defaults.headers.common)

             //修改/操作$httpProvider.defaults.headers.common对象的属性以改变$http的默认请求头配置

        })

*注意,只能操作 $httpProvider.defaults.headers.common 才有效,直接操作$httpProvider.defaults.headers是无效的.

(2)  特定请求修改(某个http请求)

直接在$http(config)的config参数中的headers项进行配置

demo:

html:

<!DOCTYPE html>
<html ng-app = 'HttpGet'>
<head>
<title>18.2 $http(1)</title>
<meta charset="utf-8">
<script src="angular.js"></script>
<script src="script.js"></script>
</head>
<body>
<div ng-controller = "dataController">
<span>{{data}}</span>
</div>
</body>
</html>

nodejs:

var express = require('express');
var app = express();
app.use(express.static(__dirname+'')); var data = 'angularjs中的$http.get'; app.get('/api/user',function(req,res){
res.send(data)
}); app.listen(3000);

(1).通过$httpProvider对整个模块的$http请求头进行修改:

var httpGet = angular.module('HttpGet',[]);
httpGet.config(function($httpProvider){
    console.log($httpProvider.defaults.headers)
    //删除后请求头里不再有 X-Requested-With 属性
delete $httpProvider.defaults.headers.common['X-Requested-With'];
    //为请求头添加Authorization属性为'code_bunny'  
$httpProvider.defaults.headers.common['Authorization'] = 'code_bunny';
});
httpGet.factory('getData',function($http,$q){
return function(){
var defer = $q.defer();
$http({
method:'get',
url:'/api/user'
}).success(function(data,status,headers,config){
defer.resolve(data);
}).error(function(data,status,headers,config){
defer.reject(data)
});
return defer.promise
}
});
httpGet.controller('dataController',function($scope,getData){
$scope.data = getData()
});

angular学习笔记(二十四)-$http(2)-设置http请求头

(2).通过$http(config)的config参数对该请求的请求头进行配置:

var httpGet = angular.module('HttpGet',[]);
httpGet.factory('getData',function($http,$q){
return function(){
var defer = $q.defer();
$http({
method:'get',
url:'/api/user',
headers: {'Authorization':'code_bunny'} //请求头里会添加Authorization属性为'code_bunny'
}).success(function(data,status,headers,config){
defer.resolve(data);
}).error(function(data,status,headers,config){
defer.reject(data)
});
return defer.promise
}
});
httpGet.controller('dataController',function($scope,getData){
$scope.data = getData()
});

完整代码地址:https://github.com/OOP-Code-Bunny/angular/tree/master/OREILLY/18.3%20%24http(1)

*注: 书上说到可以通过$httpProvider.defaults.headers.get['DNT']='1',来设置不追踪用户浏览信息,但实际尝试后发现是报错的. 

上一篇:IS_ERR、PTR_ERR、ERR_PTR


下一篇:Rabbitmq集群高可用部署详细