jingrowtools/src/shared/utils/fetchInterceptor.ts
jingrow d81526d2e0 fix: 修复刷新页面后自动登出的问题
- 修复 initAuth 中错误的 cookie 解析方式,使用 getSessionUser() 正确读取
- 重构 auth store,提取公共方法消除代码重复
  - 提取 setUserState/clearUserState 统一状态管理
  - 提取 isAuthError 统一错误判断
  - 提取 restoreUserFromStorage 恢复 localStorage 状态
  - 提取 validateAndUpdateUser 统一验证逻辑
- 优化 fetchInterceptor,添加初始化标志避免在 initAuth 期间误触发登出
- 改进错误处理,区分认证错误和网络错误,避免网络错误导致误登出
- 优化 initAuth 逻辑,先恢复 localStorage 状态避免闪烁,再验证 cookie

代码从 178 行优化到 165 行,initAuth 从 87 行减少到 28 行,消除 40+ 行重复代码
2026-01-03 00:06:11 +08:00

51 lines
1.6 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 保存原始的fetch函数
const originalFetch = window.fetch
// 标记是否正在初始化认证避免在initAuth期间误触发登出
let isInitializingAuth = false
// 导出函数,允许外部设置初始化状态
export function setInitializingAuth(value: boolean) {
isInitializingAuth = value
}
// 包装fetch函数添加401/403错误处理
window.fetch = async function(...args: Parameters<typeof fetch>): Promise<Response> {
const response = await originalFetch(...args)
// 检查响应状态码仅在401/403时处理
if (response.status === 401 || response.status === 403) {
// 如果正在初始化认证不自动登出让initAuth自己处理
if (isInitializingAuth) {
return response
}
// 延迟导入确保pinia已初始化
try {
const { useAuthStore } = await import('../stores/auth')
const { default: router } = await import('../../app/router')
const authStore = useAuthStore()
// 如果用户已登录,执行登出操作
if (authStore.isLoggedIn) {
console.warn('检测到401/403错误Cookie已过期自动退出登录')
await authStore.logout()
// 跳转到登录页(避免重复跳转)
if (router.currentRoute.value.path !== '/login') {
router.push('/login')
}
}
} catch (error) {
// 如果store还未初始化忽略错误应用启动阶段
// 这不会影响正常的API调用
}
}
return response
}
// 导出原始fetch如果需要的话
export { originalFetch as originalFetch }