Pārlūkot izejas kodu

完成登录跳转展示 account 头像

mrh 1 gadu atpakaļ
vecāks
revīzija
c70318eb76
7 mainītis faili ar 981 papildinājumiem un 113 dzēšanām
  1. 0 1
      .env
  2. 3 0
      .env.dev
  3. 2 1
      README.md
  4. 858 3
      package-lock.json
  5. 2 1
      package.json
  6. 59 27
      src/views/account/index.vue
  7. 57 80
      src/views/home/verify.vue

+ 0 - 1
.env

@@ -1,4 +1,3 @@
-# BASE_URL=192.168.1.11
 BASE_URL=swl-8l9.pages.dev
 VITE_BASE_URL=https://swl-8l9.pages.dev
 VITE_API_URLS=https://open-douyin-wk.magong.site,http://sv-v2.magong.site:8600,https://open-douyin-cf.magong.site,

+ 3 - 0
.env.dev

@@ -0,0 +1,3 @@
+BASE_URL=swl-8l9.pages.dev
+# 必须要加上 http:// ,否则框架会识别为后缀名然后地址重叠错乱
+VITE_API_URLS=http://192.168.1.32:8600,http://192.168.1.32:8600

+ 2 - 1
README.md

@@ -1,7 +1,8 @@
 # 介绍
 ```shell
 cnpm install --save-dev
-
+npm run build
+wrangler pages deploy .\dist\
 ```
 
 # 开发

Failā izmaiņas netiks attēlotas, jo tās ir par lielu
+ 858 - 3
package-lock.json


+ 2 - 1
package.json

@@ -3,12 +3,13 @@
   "private": true,
   "version": "0.0.0",
   "scripts": {
-    "dev": "vite",
+    "dev": "vite --mode dev",
     "build": "vite build",
     "preview": "vite preview",
     "start": "nodemon"
   },
   "dependencies": {
+    "amis": "^3.6.4",
     "element-plus": "^2.5.3",
     "nodemon": "^3.0.1",
     "vue": "^3.3.4",

+ 59 - 27
src/views/account/index.vue

@@ -1,33 +1,65 @@
 <template>  
     <div>  
       <h1>用户主页</h1>  
-      <!-- 使用 v-if 判断用户数据是否存在,然后显示头像和名称 -->  
-      <div v-if="nickname">  
-        <h1>Welcome, {{ nickname }}!</h1>  
-        <img :src="avatar" alt="User Avatar" />  
+      <div v-if="user">  
+        <h1>Welcome, {{ user.nickname }}!</h1>  
+        <img :src="user.avatar" alt="User Avatar" />  
       </div>  
-      <el-button round size="large" type="primary" style="width: 150px;" @click="clickbtn">立即体验{{ test }}</el-button>
-      <!-- 其他你想要展示的内容 -->  
     </div>  
-  </template>  
-
-<script setup>
-import { computed } from 'vue'
-import { useStore } from 'vuex'
-import eventBus from 'vue3-eventbus'
-
-const store = useStore()
-const user = computed(() => store.state.user)
-const nickname = computed(() => user.value?.nickname)
-const avatar = computed(() => user.value?.avatar)
-
-
-eventBus.on('login-user-data', (userData) => {
-    store.commit('setUser', userData)
-})
-
-const clickbtn = () => {
-    console.log("nickname:", nickname.value)
-    console.log("avatar:", avatar.value)
-}
+</template>  
+<script setup>  
+import { computed, ref, onMounted } from 'vue';  
+import { useStore } from 'vuex';  
+import axios from 'axios';  
+  
+const API_URLS = import.meta.env.VITE_API_URLS.split(',');  
+const store = useStore();  
+const user = ref(null);  
+const token = localStorage.getItem('token');  
+  
+function createApiClient(urls, maxRetries = 3) {  
+  let currentIndex = 0;  
+  let retries = maxRetries;  
+  
+  return {  
+    get: async (url, config = {}) => {  
+      if (retries === 0) {  
+        throw new Error('Max retries exceeded');  
+      }  
+  
+      const apiUrl = urls[currentIndex];  
+      currentIndex = (currentIndex + 1) % urls.length;  
+  
+      const instance = axios.create({  
+        baseURL: apiUrl,  
+        headers: { Authorization: `Bearer ${token}` },  
+        ...config  
+      });  
+  
+      try {  
+        const response = await instance.get(url);  
+        retries = maxRetries; // 如果请求成功,重置重试次数  
+        return response;  
+      } catch (error) {  
+        console.error(`Request to ${apiUrl} failed, ${retries} retries left...`, error);  
+        retries--;  
+        return await this.get(url, config); // 重试  
+      }  
+    }  
+  };  
+}  
+  
+const apiClient = createApiClient(API_URLS);  
+  
+const loadUserInfo = async () => {  
+  try {  
+    const response = await apiClient.get('/user_info');  
+    user.value = response.data;  
+  } catch (error) {  
+    console.error('Failed to load user info after all retries', error);  
+    // 这里可以添加进一步的错误处理  
+  }  
+};  
+  
+onMounted(loadUserInfo);  
 </script>

+ 57 - 80
src/views/home/verify.vue

@@ -1,89 +1,66 @@
-<template lang="">
-    <div id="verify-root">
-    <div class="verify" style="border-radius: 8px; box-shadow: var(--el-box-shadow-lighter);">
-        <el-row >
-            <el-col >
-                <el-text type="success" sytle="font-size: 22px;color: rgb(36, 36, 36);  "  tag="b">扫码成功</el-text>
-            </el-col>
-        </el-row>
-        <el-row>
-            <el-col>
-                <el-text>正在跳转到</el-text>  
-            </el-col>
-        </el-row>
-        <el-row>
-            <el-col>
-                <!-- 使用 v-if 控制链接的显示,只有在登录成功后才显示 -->  
-                <el-link v-if="isLoggedIn" type="primary" @click="navigateToAccount">我的主页</el-link>  
-                <!-- 添加加载状态的文本 -->  
-                <el-text v-else>{{info}}...</el-text>  
-            </el-col>
-        </el-row>
-    </div>
-    </div>
-</template>
-
-<script setup>
-import { useRouter } from 'vue-router';
-import { ref, onMounted, nextTick } from 'vue';  
-import axios from 'axios'; // 确保已经安装了axios  
-import eventBus from 'vue3-eventbus'
+<template>  
+    <div>  
+      <!-- 可以在这里添加一个加载指示器或其他UI元素 -->  
+    </div>  
+</template>  
 
+<script setup>  
+import { useRouter } from 'vue-router';  
+import { onMounted, ref } from 'vue';  
+import axios from 'axios';  
+  
+const apiUrls = import.meta.env.VITE_API_URLS.split(',');  
+let currentIndex = ref(0); // 使用Vue的ref来确保响应性  
+  
 const router = useRouter();  
-
-const isLoggedIn = ref(false);  
-const info = ref('正在验证登录信息...')
-async function tryLoginWithUrls(apiUrls, code, state, index = 0) {  
-  if (index >= apiUrls.length) {  
-    // 所有URL都尝试过了,抛出错误或处理失败  
-    throw new Error('所有服务器登录尝试均失败');  
-  }  
   
-  const apiUrl = apiUrls[index];  
-  try {  
-    const response = await axios.post(`${apiUrl}/login`, { code, state });  
-    if (response.data.message === 'success') {  
-      isLoggedIn.value = true;  
-      await nextTick();  
-      await nextTick();  
-      const userData = response.data; // 提取用户数据 
-      navigateToAccount(userData);  
-    } else {  
-      // 可以选择在这里再次尝试,或者直接失败  
-      throw new Error('登录失败: 无效的响应数据');  
-    }  
-  } catch (error) {  
-    console.error(`尝试登录服务器${apiUrl}失败:`, error);  
-    // 尝试下一个URL  
-    return tryLoginWithUrls(apiUrls, code, state, index + 1);  
-  }  
-}
+function getCurrentApiUrl() {  
+  const url = apiUrls[currentIndex.value]; // 使用.value来访问ref的值  
+  
+  // 如果当前索引已到达列表末尾,则重置为0  
+  currentIndex.value = (currentIndex.value + 1) % apiUrls.length;  
+  
+  return url;  
+}  
+  
 onMounted(async () => {  
-  try {  
-    const queryString = window.location.search;  
-    const urlParams = new URLSearchParams(queryString);  
-    const code = urlParams.get('code');  
-    const state = urlParams.get('state');  
+  // 从URL中获取code和scopes  
+  const code = router.currentRoute.value.query.code;  
+  const scopes = router.currentRoute.value.query.scopes;  
   
-    const apiUrls = import.meta.env.VITE_API_URLS.split(',');  
-    await tryLoginWithUrls(apiUrls, code, state); 
-  } catch (error) {  
-    info.value = '登录失败:' + error.message;  
-    console.error('最终登录失败:', error);  
-  }  
-});
+  if (code && scopes) {  
+    try {  
+      let retries = 3; // 设置重试次数  
+      let response;  
+  
+      while (retries--) {  
+        try {  
+          const apiUrl = getCurrentApiUrl();  
+          const loginUrl = apiUrl + '/login';  
+          response = await axios.post(loginUrl, { code, scopes });  
+  
+          // 如果请求成功,则跳出循环  
+          break;  
+        } catch (error) {  
+          console.error('Request failed, retrying with next URL...', error);  
+  
+          // 如果重试次数用完,抛出错误  
+          if (retries === 0) {  
+            throw new Error('All API requests failed');  
+          }  
+        }  
+      }  
+  
+        // 处理响应  
+        localStorage.setItem('token', response.data.token);
+          // 重定向到用户主页  
+        router.push('/account');  
 
-// 跳转函数  
-const navigateToAccount = async (userData) => {  
-  console.log("userData:",userData)
-  eventBus.emit('login-user-data', userData.data)
-  await router.push({  
-    name: 'Account', // 假设你在路由配置中给 account.vue 设置了这个名字  
-    // params: {  
-    //     userData: userData, // 将用户数据作为参数传递  
-    // },  
-  });  
-};  
+    } catch (error) {  
+      console.error('An error occurred:', error);  
+    }  
+  }  
+});  
 </script>
 
 <style lang="css" scoped>

Daži faili netika attēloti, jo izmaiņu fails ir pārāk liels