Przeglądaj źródła

feat: request.ts 增加 401 未授权处理,提示并跳转登录页

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
tanlie 2 tygodni temu
rodzic
commit
8e323f5bbd

+ 9 - 3
wishing-platform/platform-service/platform-service-mobile/src/main/resources/application.yml

@@ -15,11 +15,17 @@ spring:
 
 jwt:
   ignore-urls:
-    - /**
+    - /dgapi/mobile/user/logout
+    - /dgapi/mobile/user/login
+    - /dgapi/mobile/user/login/captcha
+    - /dgapi/mobile/wishingtree/list
+    - /dgapi/mobile/wishingtree/detail
+    - dgapi/mobile/wish/tree/**
+    - /dgapi/mobile/ext/file/**
 
 captcha:
-    width: 100
-    height: 40
+  width: 100
+  height: 40
 
 
 

+ 16 - 3
wishing-tree-h5/src/api/request.ts

@@ -1,4 +1,5 @@
-import { getStorage } from '@/utils/storage'
+import { getStorage, removeStorage } from '@/utils/storage'
+import router from '@/router'
 
 
 export interface ApiResponse<T = any> {
@@ -8,7 +9,6 @@ export interface ApiResponse<T = any> {
 }
 
 function showError(msg: string): Promise<void> {
-  // 不使用 Vant showToast(在非组件上下文中不可靠),直接用 DOM 插入
   const el = document.createElement('div')
   el.textContent = msg
   el.style.cssText =
@@ -21,6 +21,13 @@ function showError(msg: string): Promise<void> {
   return new Promise((resolve) => setTimeout(resolve, 150))
 }
 
+function handleUnauthorized() {
+  removeStorage('token')
+  showError('登录已过期,请重新登录').then(() => {
+    router.push('/login')
+  })
+}
+
 export async function request<T = any>(url: string, options?: RequestInit): Promise<ApiResponse<T>> {
 
     const token = getStorage('token')
@@ -41,6 +48,13 @@ export async function request<T = any>(url: string, options?: RequestInit): Prom
         await showError('网络连接失败,请检查网络')
         throw new Error('网络连接失败')
     }
+
+    // 401 未授权:清除 token 并跳转登录页
+    if (res.status === 401) {
+        handleUnauthorized()
+        throw new Error('未授权')
+    }
+
     // HTTP 状态码错误(500、404 等)
     if (!res.ok) {
         let errMsg = ''
@@ -68,7 +82,6 @@ export async function request<T = any>(url: string, options?: RequestInit): Prom
 
     if (json.code !== 200) {
         const errMsg = json.msg || '请求失败'
-       // await showError(errMsg)
         throw new Error(errMsg)
     }
     return json