|
@@ -0,0 +1,70 @@
|
|
|
|
|
+import axios, {
|
|
|
|
|
+ type AxiosError,
|
|
|
|
|
+ type AxiosInstance,
|
|
|
|
|
+ type AxiosRequestConfig,
|
|
|
|
|
+ type AxiosResponse,
|
|
|
|
|
+ type InternalAxiosRequestConfig
|
|
|
|
|
+} from 'axios'
|
|
|
|
|
+import { ElMessage } from 'element-plus'; // 导入 Element Plus 的 ElMessage 组件
|
|
|
|
|
+
|
|
|
|
|
+const instance: AxiosInstance = axios.create({
|
|
|
|
|
+ baseURL: import.meta.env.VITE_APP_BASE_API, // 从环境变量中获取基础 URL
|
|
|
|
|
+ timeout: 10000, // 请求超时时间
|
|
|
|
|
+ headers: {
|
|
|
|
|
+ 'Content-Type': 'application/json',
|
|
|
|
|
+ },
|
|
|
|
|
+});
|
|
|
|
|
+
|
|
|
|
|
+instance.interceptors.request.use(
|
|
|
|
|
+ (config: InternalAxiosRequestConfig) => {
|
|
|
|
|
+ // 可以在这里添加通用的请求头
|
|
|
|
|
+ return config;
|
|
|
|
|
+ },
|
|
|
|
|
+ (error:AxiosError) => {
|
|
|
|
|
+ return Promise.reject(error);
|
|
|
|
|
+ }
|
|
|
|
|
+);
|
|
|
|
|
+
|
|
|
|
|
+// 响应拦截器
|
|
|
|
|
+instance.interceptors.response.use(
|
|
|
|
|
+ (response: AxiosResponse) => {
|
|
|
|
|
+ return response.data; // 返回响应数据
|
|
|
|
|
+ },
|
|
|
|
|
+ (error:AxiosError) => {
|
|
|
|
|
+ // 处理错误
|
|
|
|
|
+ if (error.response) {
|
|
|
|
|
+ // 服务器返回了错误状态码
|
|
|
|
|
+ const { status, data } = error.response;
|
|
|
|
|
+ ElMessage.error(`请求失败,状态码: ${status},错误信息: ${data}`);
|
|
|
|
|
+ return Promise.reject(data);
|
|
|
|
|
+ } else if (error.request) {
|
|
|
|
|
+ // 请求已发出,但没有收到响应
|
|
|
|
|
+ ElMessage.error('请求已发出,但没有收到响应');
|
|
|
|
|
+ return Promise.reject({ message: 'No response received' });
|
|
|
|
|
+ } else {
|
|
|
|
|
+ // 发生了其他错误
|
|
|
|
|
+ ElMessage.error(`发生错误: ${error.message}`);
|
|
|
|
|
+ return Promise.reject({ message: error.message });
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+);
|
|
|
|
|
+export const clientGet = <T, R>(url: string, config?: AxiosRequestConfig) =>
|
|
|
|
|
+ instance.get<T, R>(url, config);
|
|
|
|
|
+
|
|
|
|
|
+export const clientPost = <T,R>(url: string, data?: T, config?: AxiosRequestConfig) =>
|
|
|
|
|
+ instance.post<T,R>(url, data, config);
|
|
|
|
|
+
|
|
|
|
|
+export const clientPut = <T,R>(url: string, data?: T, config?: AxiosRequestConfig) =>
|
|
|
|
|
+ instance.put<T,R>(url, data, config);
|
|
|
|
|
+
|
|
|
|
|
+export const clientDel = <T,R>(url: string, config?: AxiosRequestConfig) =>
|
|
|
|
|
+ instance.delete<T,R>(url, config);
|
|
|
|
|
+
|
|
|
|
|
+// 新增:专门用于发送 FormData 的 POST 请求
|
|
|
|
|
+export const clientPostFormData = <T, R>(url: string, data: T, config?: AxiosRequestConfig): Promise<R> =>
|
|
|
|
|
+ instance.post<T, R>(url, data, {
|
|
|
|
|
+ ...config,
|
|
|
|
|
+ headers: {
|
|
|
|
|
+ 'Content-Type': 'multipart/form-data', // 明确设置为 multipart/form-data
|
|
|
|
|
+ },
|
|
|
|
|
+ });
|