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
import axios from 'axios'
import { ElMessage } from 'element-plus'
 
declare module 'axios' {
  export interface AxiosRequestConfig {
    /** 可选请求:失败时不弹全局错误提示,由调用方自行降级(例如筛选项拉不到就先留空)。 */
    silent?: boolean
  }
}
 
const tokenKey = 'talent-card-admin-token'
const userKey = 'talent-card-admin-user'
 
const http = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || '',
  timeout: 12000,
})
 
http.interceptors.request.use((config) => {
  const token = localStorage.getItem(tokenKey) || sessionStorage.getItem(tokenKey)
  if (token) config.headers.Authorization = `Bearer ${token}`
  return config
})
 
http.interceptors.response.use(
  (response) => {
    const payload = response.data
    if (payload && typeof payload === 'object' && 'data' in payload) return payload.data
    return payload
  },
  (error) => {
    const isLoginRequest = String(error.config?.url || '').endsWith('/api/admin/auth/login')
    if (error.response?.status === 401 && !isLoginRequest) {
      localStorage.removeItem(tokenKey)
      localStorage.removeItem(userKey)
      sessionStorage.removeItem(tokenKey)
      sessionStorage.removeItem(userKey)
      if (window.location.pathname !== '/login') {
        const redirect = `${window.location.pathname}${window.location.search}`
        window.location.assign(`/login?redirect=${encodeURIComponent(redirect)}`)
      }
    }
    // 可选请求只降级、不弹错:筛选条件少一项不该盖住页面,更不该看起来像主流程挂了。
    if (!error.config?.silent) {
      const message = error.response?.data?.message || error.message || '请求失败'
      ElMessage.error(message)
    }
    return Promise.reject(error)
  },
)
 
export default http