2024-02-05 10:28:35 +08:00
|
|
|
|
import axios, { AxiosResponse, AxiosRequestConfig } from 'axios';
|
|
|
|
|
|
import { ResultEnum } from '@/enums/httpEnum';
|
2024-01-05 17:28:54 +08:00
|
|
|
|
// import { ErrorPageNameMap } from "@/enums/pageEnum";
|
|
|
|
|
|
// import { redirectErrorPage } from "@/utils";
|
2024-02-05 10:28:35 +08:00
|
|
|
|
import { storage } from '@/utils';
|
|
|
|
|
|
import { StorageEnum } from '@/enums/storageEnum';
|
2024-01-05 17:28:54 +08:00
|
|
|
|
|
|
|
|
|
|
const axiosInstance = axios.create({
|
|
|
|
|
|
baseURL: import.meta.env.DEV
|
|
|
|
|
|
? import.meta.env.VITE_APP_API_URL
|
|
|
|
|
|
: `http://${window.location.host}/`,
|
|
|
|
|
|
timeout: ResultEnum.TIMEOUT,
|
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
|
|
// 请求拦截器
|
|
|
|
|
|
axiosInstance.interceptors.request.use(
|
|
|
|
|
|
(config) => {
|
2024-02-05 10:28:35 +08:00
|
|
|
|
const TOKEN = storage.get(StorageEnum.ZS_ACCESS_TOKEN);
|
|
|
|
|
|
config.headers.Authorization = TOKEN;
|
2024-01-05 17:28:54 +08:00
|
|
|
|
return config;
|
|
|
|
|
|
},
|
|
|
|
|
|
(error: AxiosRequestConfig) => {
|
|
|
|
|
|
return Promise.reject(error);
|
|
|
|
|
|
}
|
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
|
|
// 响应拦截器
|
|
|
|
|
|
axiosInstance.interceptors.response.use(
|
|
|
|
|
|
(res: AxiosResponse) => {
|
2024-01-08 16:02:52 +08:00
|
|
|
|
const { message, success } = res.data as IResponse;
|
2024-01-05 17:28:54 +08:00
|
|
|
|
|
|
|
|
|
|
// 如果是文件流,直接过
|
2024-02-05 10:28:35 +08:00
|
|
|
|
if (res.config.responseType === 'blob') return Promise.resolve(res.data);
|
2024-01-05 17:28:54 +08:00
|
|
|
|
if (success) return Promise.resolve(res.data);
|
|
|
|
|
|
// 如果 success 为 false,显示服务器返回的错误消息
|
2024-02-05 10:28:35 +08:00
|
|
|
|
window['$message'].error(message || '系统错误');
|
2024-01-05 17:28:54 +08:00
|
|
|
|
|
|
|
|
|
|
// 重定向
|
|
|
|
|
|
// if (ErrorPageNameMap.get(status)) redirectErrorPage(status);
|
|
|
|
|
|
return Promise.resolve(res.data);
|
|
|
|
|
|
},
|
|
|
|
|
|
(err: AxiosResponse) => {
|
2024-02-05 10:28:35 +08:00
|
|
|
|
window['$message'].error('接口异常,请检查');
|
2024-01-05 17:28:54 +08:00
|
|
|
|
return Promise.reject(err);
|
|
|
|
|
|
}
|
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
|
|
// 导出 axios 实例
|
|
|
|
|
|
export default axiosInstance;
|