- 页面调用,post为例
this.$post(url, data, res => {
if (res.code == 1) {
-------成功返回数据
} else {
console.log(res.msg);
}
});
- 页面调用 上传图片
<input type="file" accept="image/*" @change="upPhoto($event)">
upPhoto(e) {
let imgSrc = e.srcElement.files[0];
let fordata = new FormData();
fordata.append("images", imgSrc);
if (/^image/.test(imgSrc.type)) {
this.$upload("/image/upload", fordata, res => {
if (res.status === 1) {
------上传成功
console.log(res.url;
} else {
this.$message.error("上传失败!");
}
});
} else {
this.$notify.error({
title: "错误",
message: "请上传图片格式的文件"
});
}
},
var Axios = axios.create({
baseURL: '',//本地做反向代理,所有的接口地址前面都会加上baseURL
timeout: 2000,//请求超过2s自动取消
responseType: "json",
withCredentials: true, // 是否允许带cookie这些
headers: { "Content-Type": "application/x-www-form-urlencoded;charset=utf-8" }
});
//请求前的拦截
Axios.interceptors.request.use(
config => {
// 在发送请求之前做某件事
if (config.method === "post") {
// 序列化
config.data = qs.stringify(config.data);
}
return config;
},
error => {
// error 的回调信息
return Promise.reject(error.data.error.message);
}
);
//返回状态判断(添加响应拦截器)
Axios.interceptors.response.use(
res => {
//对响应数据做些事
if (res.data.code === -1) {
}
return res.data;
},
error => {
let errorInfo = error.data.error ? error.data.error.message : error.data;
return Promise.reject(errorInfo);
}
);
function $get(Url, data, handle, err) {
Axios.get(Url, data).then(res => {
handle(res);
}).catch(error => {
if (err) {
err(error);
}
console.log(error);
});
};
function $post(Url, data, handle) {
Axios.post(Url, data).then(res => {
handle(res);
}).catch(error => {
console.log(error);
});
};
//上传图片的方法
function $upload(Url, data, handle) {
let instance = axios.create({
baseURL: '',
headers: {
'Content-Type': 'multipart/form-data'
}
});
instance.post(Url, data).then(res => {
handle(res.data);
}).catch(error => {
console.log(error);
})
};