1. angular默認的請求頭:

其中,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() });

(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',來設置不追蹤用戶瀏覽信息,但實際嘗試后發現是報錯的.
