import axios from 'axios'
|
|
/**
|
* axios 实例封装。
|
*
|
* 两个核心职责:
|
* 1. 自动携带 JWT(请求拦截器)
|
* 2. 统一解包 {code,msg,data} 并把业务错误转成异常(响应拦截器)
|
*
|
* 解包后业务代码直接拿到 data,不用每次写 res.data.data。
|
*/
|
const http = axios.create({
|
baseURL: '/api',
|
timeout: 120000
|
})
|
|
/** 未授权时的回调,由 authStore 注册,避免此处直接 import store 造成循环依赖 */
|
let onUnauthorized = null
|
|
export function setUnauthorizedHandler(handler) {
|
onUnauthorized = handler
|
}
|
|
// ---------------- 请求拦截:注入 token ----------------
|
http.interceptors.request.use(
|
(config) => {
|
// 从 localStorage 直接读,而不是 import store:
|
// 避免 store 初始化顺序问题导致的「token 还没恢复就发请求」
|
const token = localStorage.getItem('webui_token')
|
if (token) {
|
config.headers.Authorization = `Bearer ${token}`
|
}
|
return config
|
},
|
(error) => Promise.reject(error)
|
)
|
|
// ---------------- 响应拦截:解包与错误归一化 ----------------
|
http.interceptors.response.use(
|
(response) => {
|
const body = response.data
|
|
// 二进制响应(图片、文件下载)直接返回 Blob/ArrayBuffer。
|
// 不能走下面的 Result 解包:它不是 {code,msg,data} 结构,
|
// 且解包逻辑会把它当成普通对象处理。
|
if (body instanceof Blob || body instanceof ArrayBuffer) {
|
return body
|
}
|
|
// SSE 或文件下载等非 JSON 响应直接透传
|
if (body === null || typeof body !== 'object' || !('code' in body)) {
|
return body
|
}
|
|
if (body.code === 200) {
|
return body.data
|
}
|
|
// 业务层错误:统一抛出,便于调用方 try/catch
|
const error = new Error(body.msg || '请求失败')
|
error.code = body.code
|
return Promise.reject(error)
|
},
|
(error) => {
|
const status = error.response?.status
|
const body = error.response?.data
|
|
if (status === 401) {
|
// token 失效:清理本地状态并跳登录页。
|
// 通过回调而不是直接操作 router,防止 store 与 router 循环依赖。
|
if (onUnauthorized) {
|
onUnauthorized()
|
}
|
return Promise.reject(new Error(body?.msg || '登录已过期,请重新登录'))
|
}
|
|
// 把后端的 Result.msg 提取出来,让 UI 能显示有意义的提示
|
let message = body?.msg
|
if (!message) {
|
if (status === 403) message = '没有权限执行该操作'
|
else if (status === 404) message = '请求的资源不存在'
|
else if (status >= 500) message = '服务器内部错误,请查看后端日志'
|
else if (error.code === 'ECONNABORTED') message = '请求超时'
|
else if (!error.response) message = '无法连接服务器,请确认后端已启动'
|
else message = error.message
|
}
|
|
const wrapped = new Error(message)
|
wrapped.code = status
|
return Promise.reject(wrapped)
|
}
|
)
|
|
export default http
|