Explorar el Código

fix: 扫码冷启动时添加登录状态检查避免401错误

在扫码领取红包和获取红包详情前,添加 ensureTokenReady 方法检查 token 有效性。
当 token 不存在时,尝试静默登录以获取有效 token,防止冷启动时因 token 缺失导致的 401 错误。
ylong hace 19 horas
padre
commit
0ed72c4b0b
Se han modificado 1 ficheros con 32 adiciones y 1 borrados
  1. 32 1
      packet/pages/index.vue

+ 32 - 1
packet/pages/index.vue

@@ -58,6 +58,8 @@
 </template>
 
 <script>
+import { silentLogin } from '@/api/auth'
+
 export default {
     data() {
         return {
@@ -100,6 +102,17 @@ export default {
         }
     },
     methods: {
+        // 请求前确保 token 可用,避免扫码冷启动时出现 401
+        async ensureTokenReady() {
+            const token = uni.getStorageSync('token')
+            if (token) return true
+            try {
+                await silentLogin()
+                return !!uni.getStorageSync('token')
+            } catch (e) {
+                return false
+            }
+        },
         // 扫码获取红包信息
         async scanRedBag() {
             if (!this.bianhao) {
@@ -112,6 +125,15 @@ export default {
                 return;
             }
 
+            const loginReady = await this.ensureTokenReady()
+            if (!loginReady) {
+                uni.showToast({
+                    title: '登录状态失效,请稍后重试',
+                    icon: 'none'
+                });
+                return;
+            }
+
             try {
                 const res = await this.$u.api.scanRedBagAjax(this.bianhao);
                 if (res.code === 200 || res.code === 0) {
@@ -150,6 +172,15 @@ export default {
                 return;
             }
 
+            const loginReady = await this.ensureTokenReady()
+            if (!loginReady) {
+                uni.showToast({
+                    title: '登录状态失效,请稍后重试',
+                    icon: 'none'
+                });
+                return;
+            }
+
             // 显示领取中提示
             uni.showLoading({
                 title: '领取中...'
@@ -367,4 +398,4 @@ export default {
         }
     }
 }
-</style>
+</style>