fix: 未登录访问管理后台不再闪现页面,路由守卫改为服务端校验

- 守卫先经 /profile 校验 token 有效后才放行受保护路由,无效 token 直接跳登录并带 redirect 回跳
- DashboardLayout 用户信息就绪前只渲染 spinner,不渲染后台内容
- manager 路由增加 requiresAdmin 校验(role >= 10),非管理员重定向回仪表盘
- 401 拦截器改用 router.push 软跳转,避免整页刷新与双重跳转
- pinia 先于 router 安装;登录页支持 redirect 参数回跳原目标
This commit is contained in:
Sakurasan
2026-09-01 20:20:05 +08:00
parent d41bcdc371
commit a2cef00908
6 changed files with 50 additions and 13 deletions
+7 -1
View File
@@ -2,6 +2,7 @@
import axios from 'axios'
import type { AxiosError, InternalAxiosRequestConfig } from 'axios'
import { useAuthStore } from '@/stores/auth'
import router from '@/router'
const baseURL = import.meta.env.VITE_API_BASE_URL || '/api'
if (import.meta.env.DEV) { // Vite 的方式判断开发环境
@@ -49,7 +50,12 @@ service.interceptors.response.use(
if (error.response && error.response.status === 401) {
const authStore = useAuthStore();
authStore.clear();
window.location.href = '/login';
// 守卫校验期间(尚未进入受保护路由)由守卫负责跳登录;
// 这里只处理已登录状态下 token 失效的情况,且不再用 location.href 硬刷新
const current = router.currentRoute.value;
if (current.matched.some(record => record.meta.requiresAuth)) {
router.push({ path: '/login', query: { redirect: current.fullPath } });
}
}
return Promise.reject(error);
}