Axios發送請求時params和data的區別
在使用axios時,注意到配置選項中包含params和data兩者,以爲他們是相同的,實則不然。 因爲params是添加到url的請求字符串中的,用於get請求。 而data是添加到請求體(body)中的, 用於post請求。 比如對於下面的get請求: axios({ method: "get", url: "http://www.tuling123.com/openapi/api?key=20ff1803ff65429b809a310653c9daac", params: { info: "西安天氣" }, }) 如果我們將params修改爲data,顯然是不能請求成功的,因爲get請求中不存在data這個選項。
1、HTTP請求過程中,get請求:表單參數以name=value&name1=value1的形式附到url的後面;
2、post請求:表單參數是在請求體中,也是name=value&name1=value1的形式在請求體中。
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
如果使用ajax請求,在請求頭中出現 request payload導致參數的方式改變了 ,那麼解決辦法就是:
headers: {'Content-Type':'application/x-www-form-urlencoded'}
或者使用ajax設置:
$.ajaxSetup({contentType: 'application/x-www-form-urlencoded'});
這樣,問題就可以解決。