import axios from 'axios' import store from '@/store/' import { serialize } from '@/utils/util' import { ElMessage } from 'element-plus' let _retry = false // 全局未授权错误提示状态,只提示一次 const { VITE_APP_API_XT, VITE_APP_ENV, VITE_APP_URL_XT } = import.meta.env const serviceXT = axios.create({ timeout: 600000, baseURL: VITE_APP_ENV === 'development' ? VITE_APP_API_XT : VITE_APP_URL_XT, //跨域请求,允许保存cookie withCredentials: false, }) function logOutFun () { store.dispatch('FedLogOut').then(() => { const { VITE_APP_PARENT_SYSTEM, VITE_APP_ENV } = import.meta.env const isDev = VITE_APP_ENV === 'development' isDev ? router.push({ path: '/login' }) : window.location.replace(`${VITE_APP_PARENT_SYSTEM}/#/login`) }) } //http request拦截 serviceXT.interceptors.request.use( config => { const authorization = config.authorization === false const xtToken = store.state.user.xtToken if (xtToken && !authorization) { config.headers['Authorization'] = xtToken } const meta = config.meta || {} //headers中配置text请求 if (config.text === true) { config.headers['Content-Type'] = 'text/plain' } //headers中配置serialize为true开启序列化 if (config.method === 'post' && meta.isSerialize === true) { config.data = serialize(config.data) } return config }, error => { return Promise.reject(error) } ) //http response拦截 serviceXT.interceptors.response.use( res => { const status = res?.data?.code || res?.data?.error_code || res?.status const message = res?.data?.msg || res?.data?.message || '系统错误' // 如果是401并且已经重试过,直接跳转到登录页面 if ((status === 500 || status === 401) && !_retry) { // 首次报错时提示 if (!isErrorShown) { isErrorShown = true ElMessage({ message: '用户令牌过期,请重新登录', type: 'error', }) } // 清除token信息 removeToken() removeRefreshToken() // 重定向到登录页 logOutFun() return Promise.reject(new Error(message)) } // 如果请求为非200默认统一处理 if (status !== 200 && status !== 0) { ElMessage({ message: message, type: 'error', }) return Promise.reject(new Error(message)) } return res }, error => { return Promise.reject(new Error(error)) } ) export default serviceXT