From 4b5d6c751052d9597480e6d1ca453f19c1702229 Mon Sep 17 00:00:00 2001 From: ShiYu Date: Sat, 31 May 2025 23:25:08 +0800 Subject: [PATCH] feat(api): handle 401 status and improve authentication flow --- Web/src/api/fetchClient.ts | 13 +++++++++++++ Web/src/api/index.ts | 2 +- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/Web/src/api/fetchClient.ts b/Web/src/api/fetchClient.ts index 9f38072..2c4aebf 100644 --- a/Web/src/api/fetchClient.ts +++ b/Web/src/api/fetchClient.ts @@ -1,4 +1,5 @@ import type { BaseResult } from './types'; +import { clearAuthData } from './index'; export const BASE_URL = import.meta.env.PROD ? '/api' : 'http://localhost:5153/api'; export async function fetchApi( @@ -18,6 +19,18 @@ export async function fetchApi( ...options, headers, }); + + if (response.status === 401) { + clearAuthData(); + const message = encodeURIComponent('授权过期重新登录'); + window.location.href = `/login?message=${message}`; + return { + success: false, + message: '授权过期重新登录', + code: 401, + } as BaseResult; + } + const data = await response.json(); return data as BaseResult; } catch (error) { diff --git a/Web/src/api/index.ts b/Web/src/api/index.ts index ce358b2..8b6f403 100644 --- a/Web/src/api/index.ts +++ b/Web/src/api/index.ts @@ -10,7 +10,7 @@ export { register, login, getCurrentUser, - updateUserInfo, // 添加导出更新用户信息函数 + updateUserInfo, saveAuthData, clearAuthData, isAuthenticated,