本人angularjs小白,今天遇到這樣一個問題。在angularjs中發出這樣一個POST請求
$http({
method: "POST",
url: "",
params: id
}).success();
在調試中發現,參數在url上出現了,就是以?id=123124的形式出現,跟GET請求變成一樣的了,然后查了一下發現參數的寫法用GET的時候就是params,用POST/PUT/PATCH/DELETE就是data,修改后
$http({
method: "POST",
url: "",
data: id
}).success();
發現發送的參數出現在了request payload里,后端會認為參數非法無法獲?。ㄇ耙环N是序列化的參數a=bbb&c=ddd,后者是參數為一個對象)
于是查詢了POST表單請求提交時,使用的Content-Type是application/x-www-form-urlencoded,而使用原生AJAX的POST請求如果不指定請求頭RequestHeader,默認使用的Content-Type是text/plain;charset=UTF-8,在html中form的Content-type默認值:Content-type:application/x-www-form-urlencoded。修改為
$http({
method: "POST",
url: "",
data: id,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).success();
然后確實就轉成form data了,但是參數如果是對象還是不行
于是再查資料發現,如果參數是對象,還需要加上transformRequest
$http({
method: "POST",
url: "",
data: id,
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();
這樣終于可以了,其實仔細看transformRequest,也就是把參數轉成序列化的形式,所以以后如果使用的話,干脆就寫成序列化的形式就好了,省的還要再轉一道。jquery中有$.param()方法可以實現,angularjs里面不知道有沒有。