本篇主要講解$http(config)的config中的tranformRequest項和transformResponse項
1. transformRequest:
$http({ transformRequest: function(data){ //對前臺傳送的data進行處理 return data } })
這個在測試的時候遇到了很大的問題.只要經過transformRequest函式處理,哪怕是不做任何處理,node後臺都會報錯,php後臺也報同樣的錯,so,angular的這部分是有bug的.
2. transformResponse:
$http({
transformResponse: function(data){
//對後臺返回的data進行處理
return data
}
})
demo:
html:
<!DOCTYPE html> <html ng-app = 'HttpGet'> <head> <title>18.4 $http(2)</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> <script>
//自己寫了一個把字串轉換成json格式物件的方法
var $ = {}; $.serialize = function(data){ var arr1 = data.split('&'); var jsonObj = {}; for(var i=0; i<arr1.length; i++) { var arr2 = arr1[i].split('='); jsonObj[arr2[0]] = arr2[1]; } return jsonObj; }; </script> </body> </html>
js:
var jsonData = {name:"code_bunny"}; var httpGet = angular.module('HttpGet',[]); httpGet.factory('getData',function($http,$q){ return function(){ var defer = $q.defer(); $http({ method:'post', url:'/api/user', data: jsonData, headers: {'Authorization':'code_bunny'}, // transformRequest:function(data){ // console.log(data === jsonData); // return data // },
//得到的資料其實是'name=code_bunny&age=3' transformResponse:function(data){
//通過$.serialize方法轉換後,得到json格式的物件,然後獲取name屬性的值 return $.serialize(data)['name'] } }).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() });
除了在$http(config)裡配置,還可以通過$httpProvider裡進行全域性配置:
httpGet.config(function($httpProvider){ $httpProvider.defaults.transformResponse=function(data){ return $.serialize(data)['name'] } });
nodejs: (這裡用的是最新版的express,需要另外安裝載入body-parser模組,具體使用參考:https://github.com/expressjs/body-parser)
var express = require('express'); var bodyParser = require('body-parser'); var app = express(); // parse application/x-www-form-urlencoded app.use(bodyParser.urlencoded({ extended: false })); // parse application/json app.use(bodyParser.json()); app.use(express.static(__dirname+'')); var data = "name=code_bunny&age=3"; app.post('/api/user',function(req,res){ console.log(req.body);
res.send(data)
}); app.listen(3000);
完整程式碼路徑: https://github.com/OOP-Code-Bunny/angular/tree/master/OREILLY/18.4%20%24http(2)