35 lines
975 B
TypeScript
35 lines
975 B
TypeScript
import axios, { type AxiosInstance } from 'axios'
|
|
import { ElMessage } from 'element-plus'
|
|
import { useAuthStore } from '@/stores/auth'
|
|
import router from '@/router'
|
|
|
|
const baseURL = import.meta.env.VITE_API_BASE || '/api'
|
|
|
|
const client: AxiosInstance = axios.create({ baseURL, timeout: 15_000 })
|
|
|
|
client.interceptors.request.use((cfg) => {
|
|
const auth = useAuthStore()
|
|
if (auth.token) {
|
|
cfg.headers = cfg.headers ?? {}
|
|
cfg.headers.Authorization = `Bearer ${auth.token}`
|
|
}
|
|
return cfg
|
|
})
|
|
|
|
client.interceptors.response.use(
|
|
(resp) => resp,
|
|
(err) => {
|
|
const status = err?.response?.status
|
|
if (status === 401) {
|
|
const auth = useAuthStore()
|
|
auth.logout()
|
|
router.replace({ path: '/login', query: { redirect: router.currentRoute.value.fullPath } })
|
|
}
|
|
const msg = err?.response?.data?.error || err.message || '请求失败'
|
|
if (status !== 401) ElMessage.error(msg)
|
|
return Promise.reject(err)
|
|
},
|
|
)
|
|
|
|
export default client
|