fetch.js
import Vue from 'vue';
import axios from 'axios';
import { Toast } from 'vant';
import { Dialog } from 'vant';
axios.defaults.withCredentials = true
export function fetch(options) {
const toast2 = Toast.loading({
message: '获取数据中...',
forbidClick: true,
duration:0
});
let TOKEN = 'aabbcc'
options.method == 'GET' ? options.method = 'GET' : options.method = 'POST'
return new Promise((resolve, reject) => {
const instance = axios.create({
baseURL: process.env.BASE_API,
headers: {
'Content-Type': options.contentType == "multipart/form-data" ? "multipart/form-data" : "application/json",
'Authorization': TOKEN,
},
timeout: 30 * 1000,
});
instance.defaults.timeout = 30000;
instance.interceptors.response.use(
response => {
toast2.clear()
return response;
},
error => {
if(error.message.includes('timeout')){
Dialog.alert({
message: '请求超时,请稍后再试',
confirmButtonText:'我知道了'
}).then(() => {
toast2.clear()
});
return Promise.reject(error);
}
Dialog.alert({
message: '网络连接失败,请稍后再试',
confirmButtonText:'我知道了'
}).then(() => {
toast2.clear()
});
return Promise.reject(error);
});
instance(options)
.then(response => {
resolve(response);
})
.catch(error => {
toast2.clear()
var err;
err = error.response
if (err.status == 401) {
Toast({
message: 'Token失效请重新登录!',
duration: 2000
});
} else {
Toast({
message: err.data.msg,
duration: 2000
});
}
reject(err);
});
});
}