2026-04-21 22:07:29 +08:00
|
|
|
import axios from 'axios'
|
|
|
|
|
import { ElMessage } from 'element-plus'
|
|
|
|
|
import router from '@/router'
|
2026-04-30 09:49:05 +08:00
|
|
|
import { isJwtExpired } from '@/utils/jwt'
|
2026-04-21 22:07:29 +08:00
|
|
|
|
|
|
|
|
const client = axios.create({
|
|
|
|
|
baseURL: import.meta.env.VITE_API_BASE_URL ?? '/api',
|
|
|
|
|
timeout: 15000,
|
|
|
|
|
})
|
|
|
|
|
|
2026-04-28 16:08:07 +08:00
|
|
|
if (import.meta.env.DEV) {
|
|
|
|
|
client.interceptors.request.use((config) => {
|
|
|
|
|
console.debug('[tenant-platform][HTTP] request', {
|
|
|
|
|
method: config.method?.toUpperCase(),
|
|
|
|
|
url: config.baseURL ? `${config.baseURL}${config.url ?? ''}` : config.url,
|
|
|
|
|
params: config.params,
|
|
|
|
|
})
|
|
|
|
|
return config
|
|
|
|
|
})
|
|
|
|
|
client.interceptors.response.use((res) => {
|
|
|
|
|
console.debug('[tenant-platform][HTTP] response', {
|
|
|
|
|
status: res.status,
|
|
|
|
|
url: res.config.url,
|
|
|
|
|
})
|
|
|
|
|
return res
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-21 22:07:29 +08:00
|
|
|
client.interceptors.request.use((config) => {
|
|
|
|
|
const token = localStorage.getItem('token')
|
2026-04-30 09:49:05 +08:00
|
|
|
if (token && !isJwtExpired(token)) {
|
2026-04-21 22:07:29 +08:00
|
|
|
config.headers.Authorization = `Bearer ${token}`
|
2026-04-30 09:49:05 +08:00
|
|
|
} else if (token && isJwtExpired(token)) {
|
|
|
|
|
localStorage.removeItem('token')
|
|
|
|
|
if (router.currentRoute.value.path !== '/login') {
|
|
|
|
|
router.push('/login?reason=' + encodeURIComponent('登录已失效,请重新登录'))
|
|
|
|
|
}
|
|
|
|
|
return Promise.reject(new Error('登录已失效,请重新登录'))
|
2026-04-21 22:07:29 +08:00
|
|
|
}
|
|
|
|
|
return config
|
|
|
|
|
})
|
|
|
|
|
|
2026-04-30 09:49:05 +08:00
|
|
|
function handleAuthFailure(message: string) {
|
|
|
|
|
localStorage.removeItem('token')
|
|
|
|
|
if (router.currentRoute.value.path !== '/login') {
|
|
|
|
|
router.push('/login')
|
|
|
|
|
}
|
|
|
|
|
ElMessage.error(message)
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-21 22:07:29 +08:00
|
|
|
client.interceptors.response.use(
|
|
|
|
|
(res) => res,
|
|
|
|
|
(error) => {
|
2026-04-30 09:49:05 +08:00
|
|
|
const status = error.response?.status
|
|
|
|
|
if (status === 401) {
|
|
|
|
|
handleAuthFailure('登录已失效,请重新登录')
|
|
|
|
|
return Promise.reject(error)
|
|
|
|
|
}
|
|
|
|
|
if (status === 403) {
|
|
|
|
|
const msg = error.response?.data?.message ?? '当前账号无权限访问该资源'
|
2026-04-21 22:07:29 +08:00
|
|
|
ElMessage.error(msg)
|
2026-04-30 09:49:05 +08:00
|
|
|
return Promise.reject(error)
|
2026-04-21 22:07:29 +08:00
|
|
|
}
|
2026-04-30 09:49:05 +08:00
|
|
|
const msg = error.response?.data?.message ?? '请求失败'
|
|
|
|
|
ElMessage.error(msg)
|
2026-04-21 22:07:29 +08:00
|
|
|
return Promise.reject(error)
|
|
|
|
|
},
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
export default client
|