index.vue 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <template>
  2. <div>
  3. <h1>用户主页</h1>
  4. <div v-if="user">
  5. <h1>Welcome, {{ user.nickname }}!</h1>
  6. <img :src="user.avatar" alt="User Avatar" />
  7. </div>
  8. </div>
  9. </template>
  10. <script setup>
  11. import { computed, ref, onMounted } from 'vue';
  12. import { useStore } from 'vuex';
  13. import axios from 'axios';
  14. const API_URLS = import.meta.env.VITE_API_URLS.split(',');
  15. const store = useStore();
  16. const user = ref(null);
  17. const token = localStorage.getItem('token');
  18. function createApiClient(urls, maxRetries = 3) {
  19. let currentIndex = 0;
  20. let retries = maxRetries;
  21. return {
  22. get: async (url, config = {}) => {
  23. if (retries === 0) {
  24. throw new Error('Max retries exceeded');
  25. }
  26. const apiUrl = urls[currentIndex];
  27. currentIndex = (currentIndex + 1) % urls.length;
  28. const instance = axios.create({
  29. baseURL: apiUrl,
  30. headers: { Authorization: `Bearer ${token}` },
  31. ...config
  32. });
  33. try {
  34. const response = await instance.get(url);
  35. retries = maxRetries; // 如果请求成功,重置重试次数
  36. return response;
  37. } catch (error) {
  38. console.error(`Request to ${apiUrl} failed, ${retries} retries left...`, error);
  39. retries--;
  40. return await this.get(url, config); // 重试
  41. }
  42. }
  43. };
  44. }
  45. const apiClient = createApiClient(API_URLS);
  46. const loadUserInfo = async () => {
  47. try {
  48. const response = await apiClient.get('/user_info');
  49. user.value = response.data;
  50. } catch (error) {
  51. console.error('Failed to load user info after all retries', error);
  52. // 这里可以添加进一步的错误处理
  53. }
  54. };
  55. onMounted(loadUserInfo);
  56. </script>