88 lines
1.8 KiB
JavaScript
88 lines
1.8 KiB
JavaScript
import axios from "axios";
|
|
import Utils from "../utils";
|
|
import { Toast, Dialog } from 'vant';
|
|
|
|
class Axios {
|
|
|
|
constructor() {
|
|
this.requestInterceptors()
|
|
this.responseInterceptors()
|
|
}
|
|
|
|
/**
|
|
* GET请求
|
|
* @param {*} object params
|
|
* {
|
|
* url: '',
|
|
* data: {}
|
|
* }
|
|
*/
|
|
async get(params) {
|
|
this.setBaseUrl()
|
|
return await axios.get(params.url, {
|
|
params: params.data
|
|
})
|
|
}
|
|
|
|
/**
|
|
* post 请求
|
|
*/
|
|
async post(params) {
|
|
this.setBaseUrl()
|
|
return await axios.post(params.url, params.data)
|
|
}
|
|
|
|
setBaseUrl () {
|
|
axios.defaults.baseURL = Utils.checkUrl();
|
|
}
|
|
|
|
/**
|
|
* 请求拦截器
|
|
*/
|
|
requestInterceptors() {
|
|
axios.interceptors.request.use(function (config) {
|
|
// 在发送请求之前做些什么
|
|
Toast.loading({
|
|
duration: 0,
|
|
forbidClick: true,
|
|
message: '数据加载中....',
|
|
});
|
|
return config;
|
|
}, function (error) {
|
|
// 对请求错误做些什么
|
|
return Promise.reject(error);
|
|
});
|
|
}
|
|
|
|
/**
|
|
* 响应拦截器
|
|
* 对响应数据做点什么
|
|
*/
|
|
responseInterceptors() {
|
|
axios.interceptors.response.use(function (response) {
|
|
Toast.clear();
|
|
switch (response.data.code) {
|
|
case '500':
|
|
Dialog.alert({
|
|
title: '出现错误',
|
|
message: `【${response.data.code}】 ${response.data.msg}`,
|
|
});
|
|
// 出现错误,不希望返回数据给前端页面,那么这时候将程序在这里断掉
|
|
throw new Error(`【${response.data.code}】 ${response.data.msg}`)
|
|
break;
|
|
|
|
case 200:
|
|
return response.data.data;
|
|
break
|
|
}
|
|
|
|
|
|
}, function (error) {
|
|
// 对响应错误做点什么
|
|
return Promise.reject(error);
|
|
});
|
|
}
|
|
}
|
|
|
|
export default new Axios();
|