Files
Academic-Affairs-System/web/src/api/http.ts
T
2026-07-24 12:42:51 +08:00

36 lines
1.0 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import axios from 'axios'
const http = axios.create({
baseURL: import.meta.env.VITE_API_BASE_URL ?? '/api',
timeout: 15000,
})
http.interceptors.request.use((config) => {
const token = localStorage.getItem('jiaowu_token')
if (token) config.headers.Authorization = `Bearer ${token}`
return config
})
http.interceptors.response.use(
(response) => response,
(error) => {
if (error.response?.status === 401 && !error.config?.url?.endsWith('/auth/login')) {
localStorage.removeItem('jiaowu_token')
localStorage.removeItem('jiaowu_user')
window.location.assign(`/login?redirect=${encodeURIComponent(location.pathname)}`)
}
return Promise.reject(error)
},
)
export function apiErrorMessage(error: unknown) {
if (!axios.isAxiosError(error)) return '操作失败,请稍后重试。'
const data = error.response?.data
if (data?.errors) {
return Object.values(data.errors).flat().join('')
}
return data?.detail ?? data?.title ?? '操作失败,请检查网络连接。'
}
export default http