diff --git a/src/api/axiosInstance.ts b/src/api/axiosInstance.ts index eac2538..e334774 100644 --- a/src/api/axiosInstance.ts +++ b/src/api/axiosInstance.ts @@ -1,5 +1,6 @@ import axios from 'axios'; -import { useAuthStore } from '../store/userStore'; +import { userStore } from '../store/userStore'; +import router from '../router'; // 创建axios实例 const apiClient = axios.create({ @@ -12,7 +13,7 @@ const apiClient = axios.create({ // 请求拦截器 apiClient.interceptors.request.use( async (config) => { - const store = useAuthStore(); + const store = userStore(); const accessToken = store.accessToken; if (accessToken) { @@ -37,15 +38,15 @@ apiClient.interceptors.response.use( originalRequest._retry = true; try { - const store = useAuthStore(); + const store = userStore(); await store.refreshTokenMethod(); // 重试原始请求 originalRequest.headers.Authorization = `Bearer ${store.accessToken}`; return apiClient(originalRequest); } catch (refreshError) { - // 刷新token失败,跳转到登录页 - window.location.href = '/login'; + // 刷新token失败,使用router跳转到登录页 + router.push({ name: 'login' }); return Promise.reject(refreshError); } } diff --git a/src/router/index.ts b/src/router/index.ts index 0c4c68c..b041033 100644 --- a/src/router/index.ts +++ b/src/router/index.ts @@ -22,12 +22,20 @@ const router = createRouter({ ] }) + router.beforeEach((to, from, next) => { const userStore = useUserStore() - if (to.meta.requiresAuth && !userStore.isAuthenticated) { + // 如果路由需要认证但用户未登录 + if (to.meta.requiresAuth && !userStore.isLoggedIn) { next({ name: 'login' }) - } else { + } + // 如果用户已登录但访问登录页 + else if (to.name === 'login' && userStore.isLoggedIn) { + next({ name: 'manage' }) + } + // 其他情况正常导航 + else { next() } })