request.ts 4.21 KB
/**
 * Axios 请求封装
 */

import type {
	AxiosError,
	AxiosInstance,
	AxiosRequestConfig,
	AxiosResponse,
	InternalAxiosRequestConfig,
} from "axios";

import axios from "axios";

import { clearAuth, getToken } from "./auth";

// 创建 axios 实例
const service: AxiosInstance = axios.create({
	baseURL: import.meta.env.VITE_API_BASE_URL || "/api",
	timeout: 30_000,
	headers: {
		"Content-Type": "application/json",
	},
});

// 请求拦截器
service.interceptors.request.use(
	(config: InternalAxiosRequestConfig) => {
		// 添加 token
		const token = getToken();
		if (token && config.headers) {
			config.headers.Authorization = `${token}`;
		}

		// 添加时间戳防止缓存
		if (config.method === "get" || config.method === "GET") {
			config.params = {
				...config.params,
				_t: Date.now(),
			};
		}

		return config;
	},
	(error: AxiosError) => {
		console.error("请求错误:", error);
		return Promise.reject(error);
	},
);

// 响应拦截器
service.interceptors.response.use(
	(response: AxiosResponse) => {
		const res = response.data;

		// 根据实际后端接口规范调整
		// 假设后端返回格式: { code: number, data: any, message: string }
		if (res && typeof res === "object" && "code" in res) {
			const code = res.code as number;
			if (code !== undefined && code !== 200 && code !== 0) {
				const message = (res.message as string) || "未知错误";
				console.error("接口错误:", message);

				// 401: 未授权
				if (code === 401) {
					handleUnauthorized();
				}

				// 403: 无权限
				if (code === 403) {
					console.error("无权限访问");
				}

				return Promise.reject(new Error(message || "接口请求失败"));
			}
		}

		return res;
	},
	(error: AxiosError) => {
		console.error("响应错误:", error);

		if (error.response) {
			const { status, data } = error.response;

			switch (status) {
				case 401: {
					handleUnauthorized();
					break;
				}
				case 403: {
					console.error("无权限访问");
					break;
				}
				case 404: {
					console.error("请求的资源不存在");
					break;
				}
				case 500: {
					console.error("服务器内部错误");
					break;
				}
				default: {
					console.error("请求失败:", data);
				}
			}
		} else if (error.request) {
			console.error("网络错误,请检查网络连接");
		} else {
			console.error("请求配置错误:", error.message);
		}

		return Promise.reject(error);
	},
);

/**
 * 处理未授权
 */
const handleUnauthorized = () => {
	console.warn("登录已过期,请重新登录");
	clearAuth();

	// 跳转到登录页
	if (window.location.pathname !== "/login") {
		window.location.href = "/login";
	}
};

/**
 * 通用请求方法
 * 注意:响应拦截器已处理数据提取,直接返回 data
 */
export const request = <T = any>(config: AxiosRequestConfig): Promise<T> => {
	return service.request<T, T>(config) as Promise<T>;
};

/**
 * GET 请求
 * 注意:响应拦截器已处理数据提取,直接返回 data
 */
export const get = <T = any>(
	url: string,
	params?: Record<string, any>,
	config?: AxiosRequestConfig,
): Promise<T> => {
	return service.get<T, T>(url, { params, ...config }) as Promise<T>;
};

/**
 * POST 请求
 * 注意:响应拦截器已处理数据提取,直接返回 data
 */
export const post = <T = any>(
	url: string,
	data?: any,
	config?: AxiosRequestConfig,
): Promise<T> => {
	return service.post<T, T>(url, data, config) as Promise<T>;
};

/**
 * PUT 请求
 * 注意:响应拦截器已处理数据提取,直接返回 data
 */
export const put = <T = any>(
	url: string,
	data?: any,
	config?: AxiosRequestConfig,
): Promise<T> => {
	return service.put<T, T>(url, data, config) as Promise<T>;
};

/**
 * DELETE 请求
 * 注意:响应拦截器已处理数据提取,直接返回 data
 */
export const del = <T = any>(
	url: string,
	params?: Record<string, any>,
	config?: AxiosRequestConfig,
): Promise<T> => {
	return service.delete<T, T>(url, { params, ...config }) as Promise<T>;
};

/**
 * PATCH 请求
 * 注意:响应拦截器已处理数据提取,直接返回 data
 */
export const patch = <T = any>(
	url: string,
	data?: any,
	config?: AxiosRequestConfig,
): Promise<T> => {
	return service.patch<T, T>(url, data, config) as Promise<T>;
};

export default service;