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);
})

