import axios from 'axios' import type { AxiosInstance, AxiosError, AxiosRequestConfig, InternalAxiosRequestConfig, AxiosResponse } from 'axios' import { ElMessage, ElLoading, ElNotification } from 'element-plus' import { ResultEnum, ResultData, ContentType } from './interface/index' import { GlobalStore } from '@/stores/index' import router from '@/router/index' type LoadingType = { close?: () => void } let loadingInstance: LoadingType = {} const config = { // 默认地址请求地址,可在 .env.*** 文件中修改 // baseURL: import.meta.env.VITE_BZD_ERP_APP_API as string, // 设置超时时间(10s) timeout: ResultEnum.TIMEOUT as number, // 跨域时候允许携带凭证 withCredentials: true, headers: { 'Content-Type': ContentType.URLENCODED } } class RequestHttp { service: AxiosInstance public constructor(config: AxiosRequestConfig) { // 实例化axios this.service = axios.create(config) /** * @description 请求拦截器 * 客户端发送请求 -> [请求拦截器] -> 服务器 * token校验(JWT) : 接受服务器返回的token,存储到vuex/pinia/本地储存当中 */ this.service.interceptors.request.use( (config: InternalAxiosRequestConfig) => { // 开始loading loadingInstance = ElLoading.service({ lock: true, text: 'Loading', background: 'rgba(0, 0, 0, 0.7)' }) // 加入token // if (globalStore.GET_User_tokey) { // config.headers['User_tokey'] = globalStore.GET_User_tokey // } return config }, (err: any) => err ) /** * @description 响应拦截器 * 服务器换返回信息 -> [拦截统一处理] -> 客户端JS获取到信息 */ this.service.interceptors.response.use( (response: AxiosResponse) => { const { data } = response const globalStore = GlobalStore() // * 在请求结束后,并关闭请求 loading loadingInstance.close && loadingInstance.close() // 无权限访问 || 登录密码错误(code == 202) // if (data.Code === ResultEnum.ROLE) { // // router.replace('/404') // return Promise.reject(data) // } // * 登陆失效(code == 201) if (data.Code === ResultEnum.OVERDUE) { ElNotification.error({ title: '登陆失效', message: data.Msg, position: 'bottom-right' }) globalStore.SET_User_Tokey('') localStorage.clear() router.replace('/login') return Promise.reject(data) } // * 全局错误信息拦截(防止下载文件得时候返回数据流,没有code,直接报错) if (data.Code && data.Code !== ResultEnum.SUCCESS) { ElMessage.error(data.Msg) return Promise.reject(data) } // * 成功请求(在页面上除非特殊情况,否则不用在页面处理失败逻辑) return data }, async (error: AxiosError) => { loadingInstance.close && loadingInstance.close() // 请求超时 && 网络错误单独判断,没有 response if (error.message.indexOf('timeout') !== -1) ElMessage.error('请求超时!请您稍后重试') if (error.message.indexOf('Network Error') !== -1) ElMessage.error('网络错误!请您稍后重试') return Promise.reject(error) } ) } // * 常用请求方法封装 get(url: string, params?: object, _object = {}): Promise> { return this.service.get(url, { params, ..._object }) } post(url: string, params?: object, _object = {}): Promise> { return this.service.post(url, params, _object) } put(url: string, params?: object, _object = {}): Promise> { return this.service.put(url, params, _object) } delete(url: string, params?: any, _object = {}): Promise> { return this.service.delete(url, { params, ..._object }) } } export default new RequestHttp(config)