44 lines
1.0 KiB
TypeScript
44 lines
1.0 KiB
TypeScript
/**
|
|
* API 客户端配置
|
|
* 封装 Axios 实例,配置拦截器和 Token 管理
|
|
*/
|
|
import axios, { AxiosError, InternalAxiosRequestConfig } from 'axios';
|
|
import { useAuthStore } from '@/store/authStore';
|
|
|
|
// 创建 Axios 实例
|
|
const apiClient = axios.create({
|
|
baseURL: '/api/v1',
|
|
timeout: 10000,
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
},
|
|
});
|
|
|
|
// 请求拦截器:添加 Token
|
|
apiClient.interceptors.request.use(
|
|
(config: InternalAxiosRequestConfig) => {
|
|
const token = localStorage.getItem('access_token');
|
|
if (token && config.headers) {
|
|
config.headers.Authorization = `Bearer ${token}`;
|
|
}
|
|
return config;
|
|
},
|
|
(error: AxiosError) => {
|
|
return Promise.reject(error);
|
|
}
|
|
);
|
|
|
|
// 响应拦截器:处理未授权状态
|
|
apiClient.interceptors.response.use(
|
|
(response) => response,
|
|
async (error: AxiosError) => {
|
|
if (error.response?.status === 401) {
|
|
useAuthStore.getState().clearAuth();
|
|
}
|
|
|
|
return Promise.reject(error);
|
|
}
|
|
);
|
|
|
|
export default apiClient;
|