本篇主要讲解$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)