49 lines
1.3 KiB
TypeScript
49 lines
1.3 KiB
TypeScript
|
|
import axios, { AxiosResponse, AxiosRequestConfig } from "axios";
|
|||
|
|
import { ResultEnum } from "@/enums/httpEnum";
|
|||
|
|
// import { ErrorPageNameMap } from "@/enums/pageEnum";
|
|||
|
|
// import { redirectErrorPage } from "@/utils";
|
|||
|
|
|
|||
|
|
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) => {
|
|||
|
|
return config;
|
|||
|
|
},
|
|||
|
|
(error: AxiosRequestConfig) => {
|
|||
|
|
return Promise.reject(error);
|
|||
|
|
}
|
|||
|
|
);
|
|||
|
|
|
|||
|
|
// 响应拦截器
|
|||
|
|
axiosInstance.interceptors.response.use(
|
|||
|
|
(res: AxiosResponse) => {
|
|||
|
|
const { message, success } = res.data as {
|
|||
|
|
success: boolean;
|
|||
|
|
message: string;
|
|||
|
|
};
|
|||
|
|
|
|||
|
|
// 如果是文件流,直接过
|
|||
|
|
if (res.config.responseType === "blob") return Promise.resolve(res.data);
|
|||
|
|
if (success) return Promise.resolve(res.data);
|
|||
|
|
// 如果 success 为 false,显示服务器返回的错误消息
|
|||
|
|
window["$message"].error(message || "系统错误");
|
|||
|
|
|
|||
|
|
// 重定向
|
|||
|
|
// if (ErrorPageNameMap.get(status)) redirectErrorPage(status);
|
|||
|
|
return Promise.resolve(res.data);
|
|||
|
|
},
|
|||
|
|
(err: AxiosResponse) => {
|
|||
|
|
window["$message"].error("接口异常,请检查");
|
|||
|
|
return Promise.reject(err);
|
|||
|
|
}
|
|||
|
|
);
|
|||
|
|
|
|||
|
|
// 导出 axios 实例
|
|||
|
|
export default axiosInstance;
|