第一步 引入 & 挂载在Vue.prototype上
import axios from "axios";
Vue.prototype.$http = axios;
get请求
this.$http.get('xxx').then((res)=>{}).catch((err)=>{})
this.$http.get('xxx',{params:{id:123456,page:1,limit:10}}) // https://cnodejs.org/api/v1/topics?page=1&limit=10
this.$http.get(`xxx/${this.$route.params.id}`) // https://cnodejs.org/api/v1/topics/123
post请求
- post的请求参数是以键值对的形式存在请求体里,用qs.stringify()就是把传入的对象转换为formdata
需要用到
qs.stringify,qs.stringify的作用是让默认的json格式参数转换成表单格式参数
- axios默认的
content-type是application/json{name:xxx,age:xxx} qs.stringify能够让content-type变成application/x-www-form-urlencoded即formdataqs.stringify作用就是帮你自动将对象用&符号拼接起来- 实际上是否需要用qs去序列化参数完全取决于后端要怎么接受数据
import Qs from 'qs'
var data = Qs.stringify({"matterIds":"1,2,3"});
this.$http.post(url,data, {headers:{'Content-Type':'application/x-www-form-urlencoded'}}).then((res)=>{
console.log(res)
})
全局配置 post 请求的content-type
- 全局配置就可以避免每次都设置 header
//配置post请求的content-type (post提交表单的content-type就是application/x-www-form-urlencoded)
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';