1.问题:
后端接收不到AngularJs中$http.post发送的数据,总是显示为null
示例代码:

$http.post(/admin/KeyValue/GetListByPage,
{
pageindex: 1,
pagesize: 8
})
.success(function(){
alert("Mr靖");
});

代码没有错,但是在后台却接收不到数据,这是为什么呢?
用火狐监控:参数是JSON格式
用谷歌监控:传参方式是request payload
可以发现传参方式是request payload,参数格式是json,而并非用的是form传参,所以在后台用接收form数据的方式接收参数就接收不到了
POST表单请求提交时,使用的Content-Type是application/x-www-form-urlencoded,而使用原生AJAX的POST请求如果不指
定请求头RequestHeader,默认使用的Content-Type是text/plain;charset=UTF-8,而此处的Content-Type是:
2.解决方法:
直接上代码:

//要通过post传递的参数
var data = {
pageindex: 1,
pagesize: 8,
},
//post请求的地址
url = "/admin/KeyValue/GetListByPage",
//将参数传递的方式改成form
postCfg = {
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
transformRequest: function (data) {
return $.param(data);
}
};
//发送post请求,获取数据
$http.post(url, data, postCfg)
.success(function (response) {
alert("Mr靖");
});

接下来再看监视工具:
火狐监视:参数类型已经变成表单数据
谷歌监视:
现在传参方式就变成form方式了,然后后端就可以正常接收参数了!
或者:
$http({
method:'post',
url:'post.php',
data:{name:"aaa",id:1,age:20},
headers:{'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for(var p in obj){
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
}
return str.join("&");
}
}).success(function(req){
console.log(req);
})