初步完成了路由逻辑

This commit is contained in:
carry 2025-02-15 00:24:12 +08:00
parent a9e14ff5e2
commit 59ef88e4a3
2 changed files with 16 additions and 7 deletions

View File

@ -1,5 +1,6 @@
import axios from 'axios'; import axios from 'axios';
import { useAuthStore } from '../store/userStore'; import { userStore } from '../store/userStore';
import router from '../router';
// 创建axios实例 // 创建axios实例
const apiClient = axios.create({ const apiClient = axios.create({
@ -12,7 +13,7 @@ const apiClient = axios.create({
// 请求拦截器 // 请求拦截器
apiClient.interceptors.request.use( apiClient.interceptors.request.use(
async (config) => { async (config) => {
const store = useAuthStore(); const store = userStore();
const accessToken = store.accessToken; const accessToken = store.accessToken;
if (accessToken) { if (accessToken) {
@ -37,15 +38,15 @@ apiClient.interceptors.response.use(
originalRequest._retry = true; originalRequest._retry = true;
try { try {
const store = useAuthStore(); const store = userStore();
await store.refreshTokenMethod(); await store.refreshTokenMethod();
// 重试原始请求 // 重试原始请求
originalRequest.headers.Authorization = `Bearer ${store.accessToken}`; originalRequest.headers.Authorization = `Bearer ${store.accessToken}`;
return apiClient(originalRequest); return apiClient(originalRequest);
} catch (refreshError) { } catch (refreshError) {
// 刷新token失败跳转到登录页 // 刷新token失败使用router跳转到登录页
window.location.href = '/login'; router.push({ name: 'login' });
return Promise.reject(refreshError); return Promise.reject(refreshError);
} }
} }

View File

@ -22,12 +22,20 @@ const router = createRouter({
] ]
}) })
router.beforeEach((to, from, next) => { router.beforeEach((to, from, next) => {
const userStore = useUserStore() const userStore = useUserStore()
if (to.meta.requiresAuth && !userStore.isAuthenticated) { // 如果路由需要认证但用户未登录
if (to.meta.requiresAuth && !userStore.isLoggedIn) {
next({ name: 'login' }) next({ name: 'login' })
} else { }
// 如果用户已登录但访问登录页
else if (to.name === 'login' && userStore.isLoggedIn) {
next({ name: 'manage' })
}
// 其他情况正常导航
else {
next() next()
} }
}) })