2026-03-14 18:24:33 +08:00
|
|
|
|
import axios from 'axios'
|
|
|
|
|
|
import { useAuthStore } from '@/stores/authStore'
|
|
|
|
|
|
|
|
|
|
|
|
const apiClient = axios.create({
|
2026-04-04 00:31:53 +08:00
|
|
|
|
baseURL: import.meta.env.VITE_API_BASE_URL || 'https://bbs.littlelan.cn/api/v1',
|
2026-03-14 18:24:33 +08:00
|
|
|
|
timeout: 10000,
|
|
|
|
|
|
headers: {
|
|
|
|
|
|
'Content-Type': 'application/json',
|
|
|
|
|
|
},
|
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
|
|
// 请求拦截器:自动添加Token
|
|
|
|
|
|
apiClient.interceptors.request.use(
|
|
|
|
|
|
(config) => {
|
|
|
|
|
|
const { accessToken } = useAuthStore.getState()
|
|
|
|
|
|
if (accessToken) {
|
|
|
|
|
|
config.headers.Authorization = `Bearer ${accessToken}`
|
|
|
|
|
|
}
|
|
|
|
|
|
return config
|
|
|
|
|
|
},
|
|
|
|
|
|
(error) => {
|
|
|
|
|
|
return Promise.reject(error)
|
|
|
|
|
|
}
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
// 响应拦截器:处理401错误
|
|
|
|
|
|
apiClient.interceptors.response.use(
|
|
|
|
|
|
(response) => response,
|
|
|
|
|
|
(error) => {
|
|
|
|
|
|
if (error.response?.status === 401) {
|
|
|
|
|
|
// Token过期,清除认证状态并跳转登录
|
|
|
|
|
|
useAuthStore.getState().logout()
|
|
|
|
|
|
window.location.href = '/login'
|
|
|
|
|
|
}
|
|
|
|
|
|
return Promise.reject(error)
|
|
|
|
|
|
}
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
export default apiClient
|