在jQuery中,ajax請求發送post很方便的,但是在vue項目中,引入jQuery就不再適合了。
var _this = this var data = { filter:'-_id' } $.ajax({ url:'http://localhost:3000/api/goods/get', type:'post', data:data, dataType:'json', success:function(res){ _this.msg =res.data } )
而在axios中的post請求要非常注意兩個地方:
要設置合適的請求頭,一般采用x-www-form-urlencoded即可
發送的數據要序列化,特別注意啊,因為axios默認的格式是Request Payload。
當然,你也可以在引入axios時就設置默認的格式:
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
axios.post('http://localhost:3000/api/goods/get',qs.stringify(data),{ headers: { 'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8' } }).then(res=>{ _this.msg = res.data },err =>{ console.log(err) })
其中qs模塊是一件封裝進axios模塊里了,
引入axios時同時引入qs即可。
如:
import axios from 'axios' import qs from 'qs'