關于angularjs中$http POST請求參數的問題

本人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里面不知道有沒有。

查看原文>> 曼巴童鞋 - 博客 - 關于angularjs中$http POST請求參數的問題

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容