1:get请求
一般发送请求是这么写
axios.get('/user?id=12345&name=user')
.then(function (res) {
console.log(res);
}).catch(function (err) {
console.log(err);
});
但是为了方便全局统一调用封装的axios
axios.get('/user', { //params参数必写 , 如果没有参数传{}也可以
params: {
id: 12345,
name: user
}
})
.then(function (res) {
console.log(res);
})
.catch(function (err) {
console.log(err);
2.post/put/patch请求
(1) 传参格式为 formData
(全局请求头:‘Content-Type’= ‘application/x-www-form-urlencoded’)
(request的Header:‘Content-Type’= ‘multipart/form-data’)
var formData=new FormData();
formData.append('user',123456);
formData.append('pass',12345678);
axios.post("/notice",formData)
.then((res) => {return res})
.catch((err) => {return err})
(2) 传参格式为 query 形式
(全局请求头:‘Content-Type’= ‘application/x-www-form-urlencoded’)
(request的Header:‘Content-Type’= ‘application/x-www-form-urlencoded’)
使用$qs.stringify
import Qs from 'qs' //引入方式
Vue.prototype.$qs = Qs //全局加载
this.$qs.stringify(data); //使用方式
this.$qs.parse(data); //使用方式
var readyData=this.$qs.stringify({
id:1234,
name:user
});
axios.post("/notice",readyData)
.then((res) => {return res})
.catch((err) => {return err})
(3) 传参格式为 raw (JSON格式)
第一种情况: axios将JavaScript对象序列化为JSON
(全局请求头:‘Content-Type’= ‘application/x-www-form-urlencoded’)
(request的Header:‘Content-Type’= ‘application/json;charset=UTF-8’)
var readyData={
id:1234,
name:user
};
axios.post("/notice",readyData)
.then((res) => {return res})
.catch((err) => {return err})
第二种情况:
(全局请求头:‘Content-Type’= ‘application/json;charset=UTF-8’)
(request的Header:‘Content-Type’= ‘application/json;charset=UTF-8’)
var readyData=JSON.stringify({
id:1234,
name:user
});
axios.post("/notice",readyData)
.then((res) => {return res})
.catch((err) => {return err})