基本语法:
$http.post('url',{},{}).success(function(data,status,headers,config){
}).error(function(data,status,headers,config){
})
$http.post接受三个参数:
1. url: 请求的路径
2. 请求发送的数据: json对象 {name:'code_bunny'}
3. 请求配置的参数: json对象 {params: {id:5}} 这样得到的实际路径就是url?id=5
$http.post返回的对象有两个回调方法:
1. success: 请求成功的回调
2. error: 请求失败的回调
这两个方法都有四个参数:
①data: 返回的数据(或错误)
②status: 响应的状态码
③headers: 这样一个函数,具体是什么暂时不详
function (name) {
if (!headersObj) headersObj = parseHeaders(headers); if (name) {
return headersObj[lowercase(name)] || null;
} return headersObj;
}
④congfig: 请求的配置对象
{
method: "GET",
url: "/api/user",
params: {id:5}
}
下面看实例:
将请求的数据对象的name属性的值再返回,放入span标签中
html:
<!DOCTYPE html>
<html ng-app = 'HttpGet'>
<head>
<title>18.2 $http.post方法</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>
js:
var httpGet = angular.module('HttpGet',[]);
httpGet.factory('getData',function($http,$q){
return function(){
var defer = $q.defer();
$http.post('/api/user',{name:'code_bunny'}).success(function(data,status,headers,congfig){
defer.resolve(data);
}).error(function(data,status,headers,congfig){
defer.reject(data);
}); return defer.promise
}
});
httpGet.controller('dataController',function($scope,getData){
$scope.data = getData()
});
后端node代码:
var express = require('express');
var app = express();
app.use(express.bodyParser());
app.use(express.static(__dirname+'')); app.post('/api/user',function(req,res){
res.send(req.body.name)
}); app.listen(3000);
完成代码地址:https://github.com/OOP-Code-Bunny/angular/tree/master/OREILLY/18.2%20%24http.post