kongdeqiang
2026-10-12 285bf234bd50ce54fcae7bb777f8fa579b91266e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
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
 
    // 调用方显式要求「完整响应」时直接返回。
    // 典型场景是文件下载:建议文件名在 Content-Disposition 响应头里,
    // 而下面的解包逻辑只返回 body,会把响应头一起丢掉。
    if (response.config && response.config.__returnFullResponse) {
      return response
    }
 
    // 二进制响应(图片、文件下载)直接返回 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