This commit is contained in:
wangjiming
2026-08-03 09:34:08 +08:00
parent b975de02da
commit 15c4223f2c
43 changed files with 4498 additions and 234 deletions

View File

@@ -1,6 +1,5 @@
import axios, { type AxiosInstance, type AxiosRequestConfig } from 'axios'
import { ElMessage } from 'element-plus'
import { touchSessionActivity } from '@/utils/sessionActivity'
/**
* 后端统一响应格式
@@ -18,9 +17,37 @@ const service: AxiosInstance = axios.create({
timeout: 30000,
})
// 请求拦截器
/**
* 从 localStorage 取当前用户 token登录时后端返回 platform-token-{user_id})。
* 后端鉴权中间件依赖此 header 解析当前用户身份。
*/
function getAuthToken(): string | null {
const USER_STORAGE_KEY = 'currentUser'
const raw = localStorage.getItem(USER_STORAGE_KEY)
if (raw) {
try {
const user = JSON.parse(raw)
// 后端 login 返回的 token 格式为 platform-token-{user.id}
if (user?.id) return `platform-token-${user.id}`
} catch {
/* ignore */
}
}
// 兼容改造前 admin 会话
if (localStorage.getItem('username') === 'admin') return 'platform-token-admin'
return null
}
// 请求拦截器:注入 Authorization header
service.interceptors.request.use(
(config) => config,
(config) => {
const token = getAuthToken()
if (token) {
config.headers = config.headers || {}
config.headers['Authorization'] = `Bearer ${token}`
}
return config
},
(error) => Promise.reject(error),
)
@@ -30,12 +57,9 @@ service.interceptors.response.use(
const res = response.data as ApiResult
// 二进制流等非 JSON 响应直接返回
if (response.config.responseType === 'blob' || response.config.responseType === 'arraybuffer') {
touchSessionActivity()
return response
}
if (res.code === 0) {
// 生成进度轮询也属于用户正在使用系统,避免长任务结束后被误判为会话过期。
touchSessionActivity()
return res.data
}
// 业务错误