Browse Source

fix: 修复登录失效无法自动跳转登录页的问题

leo 1 tuần trước cách đây
mục cha
commit
5f49d03a25
1 tập tin đã thay đổi với 34 bổ sung13 xóa
  1. 34 13
      util/api.js

+ 34 - 13
util/api.js

@@ -1,4 +1,35 @@
 import config from './neutral.js';
+
+// token 失效全局拦截:清除登录态并跳转登录页(并发请求去重)
+let isRedirecting = false;
+const handleTokenExpired = () => {
+  uni.removeStorageSync('session_key');
+  uni.removeStorageSync('isLink'); // 清理旧版本遗留的跳转标记
+  // 并发请求同时返回 403 时只处理一次
+  if (isRedirecting) {
+    return;
+  }
+  isRedirecting = true;
+  // 已在登录页则不重复跳转
+  const pages = getCurrentPages();
+  const currentRoute = pages.length ? pages[pages.length - 1].route : '';
+  if (currentRoute === 'pages/login/login') {
+    isRedirecting = false;
+    return;
+  }
+  uni.showToast({
+    title: '登录已过期,请重新登录!',
+    icon: 'none',
+  });
+  // reLaunch 清空页面栈,避免返回键回到已失效页面
+  uni.reLaunch({
+    url: '/pages/login/login',
+    complete: () => {
+      isRedirecting = false;
+    },
+  });
+};
+
 export const myRequest = (options) => {
   let BASE_URL = uni.getStorageSync('http');
   console.log(BASE_URL, 'my request', process.env.NODE_ENV);
@@ -54,20 +85,10 @@ export const myRequest = (options) => {
       },
       data: data,
       success: (res) => {
+        // 全局拦截:token 失效(errorCode 403),清除登录态并跳转登录页
         if (res.data.errorCode == 403) {
-          uni.removeStorageSync('session_key');
-          uni.showToast({
-            title: '登录已过期,请重新登录!',
-            icon: 'none',
-          });
-          if (uni.getStorageSync('isLink')) {
-            return false;
-          } else {
-            uni.setStorageSync('isLink', true);
-            return uni.navigateTo({
-              url: '/pages/login/login',
-            });
-          }
+          handleTokenExpired();
+          return reject(res.data.message || '登录已过期');
         }
         if (res.data.message) {
           if (