Browse Source

feat(@six/smart-pharmacy): 智慧药事系统第一版-修改请求拦截,识别 HTTP 401 后自动退出登录

cmj 1 week ago
parent
commit
06641d252d

+ 4 - 1
apps/smart-pharmacy/src/api/index.ts

@@ -24,7 +24,10 @@ export const http = createRequestClient({
   transform: transformHttpResponse,
 });
 http.interceptor('error', async (error) => {
-  if (error?.code === 401) await useAuthStore().logout();
+  if (error?.code === 401) {
+    await useAuthStore().logout();
+    return;
+  }
   message.error(error.message ?? `服务错误 (${error.code})`).then();
 });
 

+ 18 - 1
apps/smart-pharmacy/src/router/guard.ts

@@ -138,7 +138,24 @@ function setupAccessGuard(router: Router) {
 
     // 生成路由表
     // 当前登录用户拥有的角色标识列表
-    const userInfo = userStore.userInfo || (await authStore.getUserInfo());
+    let userInfo = userStore.userInfo;
+    if (!userInfo) {
+      try {
+        userInfo = await authStore.getUserInfo();
+      } catch (error: any) {
+        if (error?.code === 401) {
+          return {
+            path: LOGIN_PATH,
+            query:
+              isHomeEntryPath(to.fullPath)
+                ? {}
+                : { redirect: encodeURIComponent(to.fullPath) },
+            replace: true,
+          };
+        }
+        throw error;
+      }
+    }
     const userRoles = userInfo.roles ?? [];
 
     // 生成菜单和路由

+ 6 - 5
packages/request/src/index.ts

@@ -17,7 +17,9 @@ export default function createRequestClient(options?: SimpleAlovaOptions) {
       if (response.status > 400) {
         const message = response.statusText;
         // eslint-disable-next-line no-throw-literal
-        throw { message };
+        throw response.status === 401
+          ? { code: 401, message: message || 'Unauthorized' }
+          : { message };
       }
 
       /* prettier-ignore */
@@ -60,12 +62,11 @@ export default function createRequestClient(options?: SimpleAlovaOptions) {
     tokenAuthentication: createServerTokenAuthentication({
       refreshTokenOnSuccess: {
         async isExpired(response) {
-          return response.status === 401;
+          // 无 refreshToken 时不走刷新逻辑,避免 401 被反复重试
+          return response.status === 401 && !!store.refreshToken;
         },
         async handler(response) {
-          if (store.refreshToken) {
-            console.log(response);
-          }
+          console.log(response);
         },
         metaMatches: {
           authRole: 'refreshToken',