前端重构实现

This commit is contained in:
2025-12-22 16:38:06 +08:00
parent cd6d995d5a
commit 26574e3db7
54 changed files with 8976 additions and 0 deletions
+69
View File
@@ -0,0 +1,69 @@
import axios from 'axios';
/**
* API 配置
* 创建 axios 实例并配置拦截器
*/
// API 基础地址
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080';
/**
* 创建 axios 实例
*/
const api = axios.create({
baseURL: API_BASE_URL,
timeout: 30000,
headers: {
'Content-Type': 'application/json'
}
});
/**
* 请求拦截器
* 自动添加 token 到请求头
*/
api.interceptors.request.use(
(config) => {
const token = localStorage.getItem('access_token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
(error) => {
return Promise.reject(error);
}
);
/**
* 响应拦截器
* 统一处理响应和错误
*/
api.interceptors.response.use(
(response) => {
const { data } = response;
// 后端返回格式: { code, message, data }
if (data.code === 200 || data.code === 0) {
return data;
}
// 业务错误
return Promise.reject(new Error(data.message || '请求失败'));
},
(error) => {
// 网络错误或服务器错误
if (error.response) {
const { status, data } = error.response;
if (status === 401) {
// token 过期,清除登录状态
localStorage.removeItem('access_token');
localStorage.removeItem('refresh_token');
window.location.href = '/';
}
return Promise.reject(new Error(data?.message || `请求失败: ${status}`));
}
return Promise.reject(new Error(error.message || '网络错误'));
}
);
export default api;