第三阶段核心业务开发完成
This commit is contained in:
62
charging_web_app/src/utils/axios.ts
Normal file
62
charging_web_app/src/utils/axios.ts
Normal file
@@ -0,0 +1,62 @@
|
||||
import axios from 'axios';
|
||||
|
||||
const api = axios.create({
|
||||
baseURL: process.env.NEXT_PUBLIC_API_BASE_URL || 'http://localhost:7529/api',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
withCredentials: true, // <--- 取消注释
|
||||
});
|
||||
|
||||
// 请求拦截器:用于在每个请求发送前执行某些操作(例如,添加认证token)
|
||||
api.interceptors.request.use(
|
||||
async (config) => {
|
||||
// 假设token存储在localStorage中。实际应用中,你可能会从AuthContext或类似地方获取。
|
||||
// if (typeof window !== 'undefined') { // <--- 暂时注释掉这部分逻辑
|
||||
// const token = localStorage.getItem('authToken'); // 确保你的登录逻辑中存储了名为 'authToken' 的token
|
||||
// if (token) {
|
||||
// config.headers.Authorization = `Bearer ${token}`;
|
||||
// }
|
||||
// } // <--- 暂时注释掉这部分逻辑
|
||||
return config;
|
||||
},
|
||||
(error) => {
|
||||
return Promise.reject(error);
|
||||
}
|
||||
);
|
||||
|
||||
// 响应拦截器:用于在接收到响应后执行某些操作
|
||||
api.interceptors.response.use(
|
||||
(response) => {
|
||||
// 如果后端返回的数据结构在 data 字段中,有些项目会直接返回 response.data
|
||||
// 例如: return response.data;
|
||||
return response; // 当前返回完整的 AxiosResponse 对象
|
||||
},
|
||||
(error) => {
|
||||
// 全局错误处理
|
||||
// 例如:如果401未授权,则重定向到登录页面
|
||||
if (error.response && error.response.status === 401) {
|
||||
if (typeof window !== 'undefined') {
|
||||
// 清理认证相关的 localStorage (如果适用)
|
||||
// localStorage.removeItem('authToken');
|
||||
// localStorage.removeItem('user');
|
||||
// window.location.href = '/login';
|
||||
// 注意:直接使用 window.location.href 会导致全页面刷新。
|
||||
// 在Next.js中,更好的做法是使用router.push(),但这需要在组件上下文中,或通过事件总线/状态管理触发。
|
||||
// 对于axios拦截器这种非组件上下文,可能需要一个更复杂的解决方案来触发路由跳转,
|
||||
// 或者接受这里的全页面刷新,或者在调用api的地方具体处理401。
|
||||
console.error('Unauthorized, redirecting to login might be needed.');
|
||||
}
|
||||
}
|
||||
return Promise.reject(error);
|
||||
}
|
||||
);
|
||||
|
||||
export { api };
|
||||
|
||||
// 定义通用的后端响应格式接口,与Spring后端的BaseResponse对应
|
||||
export interface BaseResponse<T> {
|
||||
code: number; // 响应状态码,0表示成功
|
||||
data: T; // 泛型数据,可以是任何类型
|
||||
message?: string; // 可选的消息说明
|
||||
}
|
||||
Reference in New Issue
Block a user