This commit is contained in:
fuenmao
2026-10-09 16:46:35 +08:00
parent 4925c4c74d
commit 563836f789
60 changed files with 4729 additions and 2047 deletions
+23 -1
View File
@@ -2,12 +2,26 @@ import axios from 'axios'
import { clearTokens, getToken } from './auth'
type UnifiedResult<T> = {
code?: number
type?: string
message?: string
result?: T
errors?: unknown
}
let redirectingToLogin = false
function handleUnauthorized(requestAuthorization?: unknown) {
// A response from the previous session must not clear a newly signed-in session.
const currentToken = getToken()
if (currentToken && requestAuthorization !== `Bearer ${currentToken}`) return
clearTokens()
if (typeof window !== 'undefined' && window.location.pathname !== '/auth' && !redirectingToLogin) {
redirectingToLogin = true
window.location.replace('/auth')
}
}
const http = axios.create({
baseURL: '/',
timeout: 15000
@@ -22,6 +36,12 @@ http.interceptors.request.use((config) => {
http.interceptors.response.use(
((response: any) => {
const body = response.data as UnifiedResult<unknown>
if (body && typeof body === 'object') {
if (body.code === 401) {
handleUnauthorized(response.config?.headers?.Authorization)
return Promise.reject(new Error(body.message || '登录已过期,请重新登录'))
}
}
if (body && typeof body === 'object' && 'result' in body) {
if (body.type && body.type !== 'success') {
return Promise.reject(new Error(body.message || '请求失败'))
@@ -31,7 +51,9 @@ http.interceptors.response.use(
return body
}) as any,
(error) => {
if (error.response?.status === 401) clearTokens()
if (error.response?.status === 401) {
handleUnauthorized(error.config?.headers?.Authorization ?? error.response?.config?.headers?.Authorization)
}
const body = error.response?.data as UnifiedResult<unknown> | undefined
const message = body?.message || error.message || '网络请求失败'
return Promise.reject(new Error(message))