初步完成了路由逻辑
This commit is contained in:
parent
a9e14ff5e2
commit
59ef88e4a3
@ -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);
|
||||
}
|
||||
}
|
||||
|
@ -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()
|
||||
}
|
||||
})
|
||||
|
Loading…
x
Reference in New Issue
Block a user