File size: 1,151 Bytes
4bcd925 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | import axios, { type AxiosInstance, type AxiosError } from 'axios'
// 创建 axios 实例
export const apiClient: AxiosInstance = axios.create({
baseURL: import.meta.env.VITE_API_URL || '',
timeout: 30000,
withCredentials: true, // 支持 cookie 认证
})
// 请求拦截器
apiClient.interceptors.request.use(
(config) => {
// 可以在这里添加 token 等认证信息
return config
},
(error) => {
return Promise.reject(error)
}
)
// 响应拦截器
apiClient.interceptors.response.use(
(response) => {
return response.data
},
async (error: AxiosError) => {
// 统一错误处理
if (error.response?.status === 401) {
const { useAuthStore } = await import('@/stores/auth')
const authStore = useAuthStore()
authStore.isLoggedIn = false
const router = await import('@/router')
router.default.push('/login')
}
const errorMessage = error.response?.data
? (error.response.data as any).detail || (error.response.data as any).message
: error.message
return Promise.reject(new Error(errorMessage || '请求失败'))
}
)
export default apiClient
|