前端在做項目的時候會遇到后端是第三方人員開發的接口,由於前期溝通不是很明確其中會出現很多不
知名的前端bug存在,這不今天在做一個智能垃圾桶系統的時候就遇到一個問題;
問題描述:
對方給的Postman測試用例,后端接收的數據是請求頭header需要x-www-form-urlencoded格式,在
Postman里面用數據能正常返回;
然而拿到前端Vue里面去請求就報錯500;
一頓研究沒整明白,后來問了一下big佬才知道x-www-form-urlencoded格式的數據就像get請求一樣需要
拼接到url里面的。
big佬給了個解決方案如下:
this.$axios({ method: "post", url: _API_Url, data: param, headers: { "Content-Type": "application/x-www-form-urlencoded" }, transformRequest: [(data) => { let ret = ""; for (let it in data) { ret += encodeURIComponent(it) + "=" + encodeURIComponent(data[it]) + "&"; } return ret; }] }).then((res) => { if (res.data.status == 200) { this.getListDate(this.pageSize, this.currentPage); } });
總結:這樣雖然能實現功能,但是建議還是叫后端弄成json格式的方法傳