执行 GET 请求
// 向具有指定ID的用户发出请求
axios.get('/user?ID=12345')
.then(function (res) {
console.log(res);
})
.catch(function (error) {
console.log(error);
});
// 也可以通过 params 对象传递参数
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
#执行 POST 请求
axios.post('/user', {
userId:"123"
},{
headers:{
token:"abc"
}
})
.then(function (res) {
console.log(res);
})
.catch(function (error) {
console.log(error);
});
#通过配置方式发送请求
get
请求是发送参数,在params
中定义。而POST
请求是发送request body
,需要在data
中定义
// get 在params中定义
axios({
url:"pakage.json",
method:"get",
params:{
userId:"123"
},
headers:{
token:"http-test"
}
}).then(res=>{
console.log(res.data);
})
// post 在data中定义
axios({
url:"pakage.json",
method:"post",
data:{
userId:"123"
},
headers:{
token:"http-test"
}
}).then(res=>{
console.log(res.data);
})
#执行多个并发请求
function getUserAcount(){
// 返回一个promise对象
return axios.get("/user/1234");
}
function getUserPermissions(){
// 返回一个promise对象
return axios.get("/user/1234/getUserPermissions");
}
//一次性返回两个接口
axios.all([getUserAccount(),getUserPerssions()]).then(axios.spread((acct, perms) => {
// spread展开两个返回的结果
//两个请求现已完成
}))
#全局拦截
new Vue({
el:"app",
data:{
msg:""
},
// 初始化生命周期的一个函数
mounted:function(){
//拦截请求之前
axios.interceptors.request.use(config=>{
//这里做一些拦截操作,拦截用户的请求 请求之前做一些loading处理
return config;
})
//拦截响应之后处理
axios.interceptors.response.use(response=>{
//这里做一些拦截操作,响应以后做什么,在返回数据
return response;
})
},
methods: {
get: function() {
},
post:function() {
}
}
})
#请求封装、异常统一处理
vue中采用axios处理网络请求,避免请求接口重复代码,以及各种网络情况造成的异常情况的判断,采用axios请求封装和异常拦截操作
#1 axios 请求封装
// 引入axios文件包
import axios from 'axios'
// POST 方法封装 (参数处理)
export const postRequest = (url, params) => {
return axios({
method: 'post',
url: url,
data: params,
transformRequest: [function (data) {
let ret = ''
for (let it in data) {
ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
}
return ret
}],
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
}
// POST 方法封装 (文件上传)
export const uploadFileRequest = (url, params) => {
return axios({
method: 'post',
url: url,
data: params,
headers: {
'Content-Type': 'mu