在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'