feat(api): handle 401 status and improve authentication flow

This commit is contained in:
ShiYu
2025-05-31 23:25:08 +08:00
parent 06ed86da8e
commit 4b5d6c7510
2 changed files with 14 additions and 1 deletions

View File

@@ -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<T = any>(
@@ -18,6 +19,18 @@ export async function fetchApi<T = any>(
...options,
headers,
});
if (response.status === 401) {
clearAuthData();
const message = encodeURIComponent('授权过期重新登录');
window.location.href = `/login?message=${message}`;
return {
success: false,
message: '授权过期重新登录',
code: 401,
} as BaseResult<T>;
}
const data = await response.json();
return data as BaseResult<T>;
} catch (error) {

View File

@@ -10,7 +10,7 @@ export {
register,
login,
getCurrentUser,
updateUserInfo, // 添加导出更新用户信息函数
updateUserInfo,
saveAuthData,
clearAuthData,
isAuthenticated,