| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 |
- <template>
- <div>
- <h1>用户主页</h1>
- <div v-if="user">
- <h1>Welcome, {{ user.nickname }}!</h1>
- <img :src="user.avatar" alt="User Avatar" />
- </div>
- </div>
- </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>
|