import axios from "axios";
|
import {getToken} from "@/utils/auth";
|
import {ElLoading, ElMessage, ElMessageBox, ElNotification} from 'element-plus'
|
import {generate, tansParams} from '@/utils/ruoyi'
|
import errorCode from "@/utils/errorCode";
|
import cache from "@/plugins/cache";
|
import {useUserStore} from "@/store/modules/user";
|
axios.defaults.headers.head['Content-Type'] = 'application/json;charset=utf-8';
|
let baseHref = import.meta.env.VITE_APP_BASE_URL?.toString() ?? './';
|
let baseUrl = import.meta.env.VITE_APP_BASE_API?.toString();
|
const service = axios.create({
|
baseURL: baseUrl,
|
timeout: 10000,
|
})
|
|
let downloadLoadingInstance: any;
|
// 是否显示重新登录
|
let isReLoginShow: boolean;
|
|
// request拦截器
|
service.interceptors.request.use(config => {
|
|
// 是否需要设置 token
|
const isToken = config?.headers?.isToken
|
// 是否需要防止数据重复提交
|
const isRepeatSubmit = config?.headers?.repeatSubmit
|
if (getToken() && !isToken) {
|
config!.headers!['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
|
}
|
// get请求映射params参数
|
if (config.method === 'get' && config.params) {
|
let url = config.url + '?' + tansParams(config.params);
|
url = url.slice(0, -1);
|
config.params = {};
|
config.url = url;
|
}
|
if (!isRepeatSubmit && (config.method === 'post' || config.method === 'put')) {
|
const requestObj = {
|
url: config.url,
|
data: typeof config.data === 'object' ? JSON.stringify(config.data) : config.data,
|
time: new Date().getTime()
|
}
|
const sessionObj = cache.session.getJSON('sessionObj')
|
if (sessionObj === undefined || sessionObj === null || sessionObj === '') {
|
cache.session.setJSON('sessionObj', requestObj)
|
} else {
|
const s_url = sessionObj.url; // 请求地址
|
const s_data = sessionObj.data; // 请求数据
|
const s_time = sessionObj.time; // 请求时间
|
const interval = 1000; // 间隔时间(ms),小于此时间视为重复提交
|
if (s_data === requestObj.data && requestObj.time - s_time < interval && s_url === requestObj.url) {
|
const message = '数据正在处理,请勿重复提交';
|
console.warn(`[${s_url}]: ` + message)
|
return Promise.reject(new Error(message))
|
} else {
|
cache.session.setJSON('sessionObj', requestObj)
|
}
|
}
|
}
|
return config
|
}, error => {
|
console.log(error)
|
Promise.reject(error)
|
})
|
let loginOutTxt='登录状态已过期,请重新登录!';
|
// 响应拦截器
|
service.interceptors.response.use(res => {
|
// 未设置状态码则默认成功状态
|
const code = res.data.code || 200;
|
// 获取错误信息
|
const msg = errorCode[code] || res.data.msg || errorCode['default']
|
// 二进制数据则直接返回
|
if (res.request.responseType === 'blob' || res.request.responseType === 'arraybuffer') {
|
return res.data
|
}
|
if (code === 401) {
|
if (!isReLoginShow) {
|
isReLoginShow = true;
|
if (window.location.href.includes("/login")) {
|
return Promise.reject(loginOutTxt)
|
}
|
ElMessageBox.confirm(loginOutTxt, '系统提示', {
|
confirmButtonText: '重新登录',
|
cancelButtonText: '取消',
|
type: 'warning'
|
}
|
).then(() => {
|
isReLoginShow = false;
|
const userStore = useUserStore();
|
userStore.LogOut().then(() => {
|
// 如果是登录页面不需要重新加载
|
if (!window.location.href.includes("login")) {
|
location.href = baseHref+'/login';
|
}
|
})
|
}).catch(() => {
|
isReLoginShow = false;
|
});
|
}
|
return Promise.reject(loginOutTxt)
|
} else if (code === 500) {
|
ElMessage({
|
message: msg,
|
type: 'error'
|
})
|
return Promise.reject(new Error(msg))
|
} else if (code !== 201 && code !== 200) {
|
ElNotification.error({
|
title: msg
|
})
|
return Promise.reject('error')
|
} else {
|
return Promise.resolve(res.data)
|
}
|
},
|
error => {
|
console.log('err' + error)
|
let {message} = error;
|
if (message == "Network Error") {
|
message = "后端接口连接异常";
|
} else if (message.includes("timeout")) {
|
message = "系统接口请求超时";
|
} else if (message.includes("Request failed with status code")) {
|
message = "系统接口" + message.substr(message.length - 3) + "异常";
|
}
|
ElMessage({
|
message: message,
|
type: 'error',
|
duration: 5 * 1000
|
})
|
return Promise.reject(error)
|
}
|
)
|
|
const hashMap = new Map();
|
export function download(url: string, params: any, filename?: string) {
|
if (!params){
|
params = {}
|
}
|
params['exportKey'] = generate();
|
service.get(url,{params}).then(async(data :any)=>{
|
const {exportKey} = params;
|
let elNotification = ElNotification({
|
message:'数据导出中,稍后...',
|
type: 'warning',
|
duration:0,
|
onClose:()=>{
|
let newVar = hashMap.get(exportKey);
|
//有值代表手动关闭
|
if (newVar){
|
clearDownload(exportKey)
|
}
|
}
|
});
|
hashMap.set(exportKey,elNotification);
|
getDownloadName(exportKey);
|
}).catch((r) => {
|
console.error(r)
|
ElMessage.error('下载文件出现错误,请联系管理员!')
|
})
|
}
|
function getDownloadName(exportKey:string){
|
let params = {exportKey:exportKey}
|
service.get('common/getDownloadName',{params}).then(async(data :any)=>{
|
if (data.code === 200) {
|
let newVar = hashMap.get(exportKey);
|
if (newVar){
|
if(data.data ==-1){
|
ElMessage({message: '导出异常', type: 'success'})
|
}else{
|
let msg = data.data;
|
window.location.href = baseUrl + "/common/download?fileName=" + encodeURI(msg) + "&delete=" + true;
|
hashMap.delete(exportKey);
|
newVar.close();
|
ElNotification({message:'数据导出成功', type: 'success',});
|
}
|
}
|
}else{
|
setTimeout(()=>{
|
getDownloadName(exportKey);
|
},3000)
|
}
|
})
|
}
|
|
function clearDownload(exportKey:string){
|
let params = {exportKey:exportKey}
|
service.get('common/clearDownload',{params}).then(async(data :any)=>{
|
if (data.code === 200) {
|
let newVar = hashMap.get(exportKey);
|
hashMap.delete(exportKey);
|
newVar.close();
|
ElMessage({message: '取消下载成功', type: 'success', duration: 5 * 1000})
|
}
|
})
|
}
|
|
export type requestType = (...any: any) => Promise<any>
|
|
export default service
|