/** * bx 报销模块 HTTP 客户端 * 协议:code === 0、msg、data.rows(与门户 request code===200 分离) */ import axios, { type AxiosRequestConfig, type InternalAxiosRequestConfig } from 'axios' import { ElMessage } from 'element-plus' import { useUserStore } from '@/store/modules/user' export interface BxApiResponse { code: number msg: string data?: T } const bxAxios = axios.create({ baseURL: '/api', timeout: 60000, headers: { 'Content-Type': 'application/json' } }) bxAxios.interceptors.request.use((config: InternalAxiosRequestConfig) => { const token = useUserStore().accessToken if (token) { config.headers.Authorization = `Bearer ${token}` } return config }) bxAxios.interceptors.response.use( async (res) => { if (res.config.responseType === 'blob') { const contentType = String(res.headers['content-type'] || '') if (contentType.includes('application/json')) { const text = await (res.data as Blob).text() try { const json = JSON.parse(text) as BxApiResponse if (json.code !== 0) { ElMessage.error(json.msg || '请求失败') return Promise.reject(new Error(json.msg)) } } catch { /* 非 JSON blob 直出 */ } } return res.data } const body = res.data as BxApiResponse if (body?.code !== undefined && body.code !== 0) { ElMessage.error(body.msg || '请求失败') return Promise.reject(new Error(body.msg || '请求失败')) } return body }, async (err) => { if (err.response?.status === 401) { const userStore = useUserStore() await userStore.logOut() } else { const detail = err.response?.data?.detail || err.response?.data?.msg ElMessage.error(detail || err.message || '网络异常') } return Promise.reject(err) } ) function request(config: AxiosRequestConfig) { return bxAxios.request>(config) } const bxRequest = { get(url: string, config?: AxiosRequestConfig) { return request({ ...config, url, method: 'GET' }) }, post(url: string, data?: unknown, config?: AxiosRequestConfig) { return request({ ...config, url, method: 'POST', data }) }, put(url: string, data?: unknown, config?: AxiosRequestConfig) { return request({ ...config, url, method: 'PUT', data }) }, delete(url: string, config?: AxiosRequestConfig) { return request({ ...config, url, method: 'DELETE' }) } } export default bxRequest