fix: 修复动态路由重定向问题

This commit is contained in:
chansee97 2025-08-18 22:40:29 +08:00
parent e66e4fb17c
commit 03a7891ed4
5 changed files with 77 additions and 48 deletions

2
.env
View File

@ -20,7 +20,7 @@ VITE_STORAGE_PREFIX =
VITE_COPYRIGHT_INFO = Copyright © 2024 chansee97
# 自动刷新token
VITE_AUTO_REFRESH_TOKEN = Y
VITE_AUTO_REFRESH_TOKEN = N
# 默认多语言 enUS | zhCN
VITE_DEFAULT_LANG = enUS

View File

@ -22,6 +22,19 @@ export function setupRouterGuard(router: Router) {
// 判断有无TOKEN,登录鉴权
const isLogin = Boolean(local.get('accessToken'))
// 处理根路由重定向
if (to.name === 'root') {
if (isLogin) {
// 已登录,重定向到首页
next({ path: import.meta.env.VITE_HOME_PATH, replace: true })
}
else {
// 未登录,重定向到登录页
next({ path: '/login', replace: true })
}
return
}
// 如果是login路由直接放行
if (to.name === 'login') {
// login页面不需要任何认证检查直接放行
@ -40,17 +53,25 @@ export function setupRouterGuard(router: Router) {
}
// 判断路由有无进行初始化
if (!routeStore.isInitAuthRoute) {
await routeStore.initAuthRoute()
// 动态路由加载完回到根路由
if (to.name === '404') {
// 等待权限路由加载好了,回到之前的路由,否则404
next({
path: to.fullPath,
replace: true,
query: to.query,
hash: to.hash,
})
if (!routeStore.isInitAuthRoute && to.name !== 'login') {
try {
await routeStore.initAuthRoute()
// 动态路由加载完回到根路由
if (to.name === '404') {
// 等待权限路由加载好了,回到之前的路由,否则404
next({
path: to.fullPath,
replace: true,
query: to.query,
hash: to.hash,
})
return
}
}
catch {
// 如果路由初始化失败(比如 401 错误),重定向到登录页
const redirect = to.fullPath !== '/' ? to.fullPath : undefined
next({ path: '/login', query: redirect ? { redirect } : undefined })
return
}
}

View File

@ -5,7 +5,6 @@ export const routes: RouteRecordRaw[] = [
{
path: '/',
name: 'root',
redirect: '/appRoot',
children: [
],
},

View File

@ -19,9 +19,11 @@ const { onAuthRequired, onResponseRefreshToken } = createServerTokenAuthenticati
// 服务端判定token过期
refreshTokenOnSuccess: {
// 当服务端返回401时表示token过期
isExpired: (response, method) => {
isExpired: async (response, method) => {
const res = await response.clone().json()
const isExpired = method.meta && method.meta.isExpired
return response.status === 401 && !isExpired
return (response.status === 401 || res.code === 401) && !isExpired
},
// 当token过期时触发在此函数中触发刷新token

View File

@ -39,23 +39,22 @@ export const useRouteStore = defineStore('route-store', {
async initRouteInfo() {
if (import.meta.env.VITE_ROUTE_LOAD_MODE === 'dynamic') {
const userInfo = local.get('userInfo')
try {
// Get user's route
const result = await fetchUserRoutes({
id: 1,
})
if (!userInfo || !userInfo.id) {
const authStore = useAuthStore()
authStore.logout()
return
if (!result.isSuccess || !result.data) {
throw new Error('Failed to fetch user routes')
}
return result.data
}
catch (error) {
console.error('Failed to initialize route info:', error)
throw error
}
// Get user's route
const { data } = await fetchUserRoutes({
id: userInfo.id,
})
if (!data)
return
return data
}
else {
this.rowRoutes = staticRoutes
@ -65,25 +64,33 @@ export const useRouteStore = defineStore('route-store', {
async initAuthRoute() {
this.isInitAuthRoute = false
// Initialize route information
const rowRoutes = await this.initRouteInfo()
if (!rowRoutes) {
window.$message.error($t(`app.getRouteError`))
return
try {
// Initialize route information
const rowRoutes = await this.initRouteInfo()
if (!rowRoutes) {
const error = new Error('Failed to get route information')
window.$message.error($t(`app.getRouteError`))
throw error
}
this.rowRoutes = rowRoutes
// Generate actual route and insert
const routes = createRoutes(rowRoutes)
router.addRoute(routes)
// Generate side menu
this.menus = createMenus(rowRoutes)
// Generate the route cache
this.cacheRoutes = generateCacheRoutes(rowRoutes)
this.isInitAuthRoute = true
}
catch (error) {
// 重置状态并重新抛出错误
this.isInitAuthRoute = false
throw error
}
this.rowRoutes = rowRoutes
// Generate actual route and insert
const routes = createRoutes(rowRoutes)
router.addRoute(routes)
// Generate side menu
this.menus = createMenus(rowRoutes)
// Generate the route cache
this.cacheRoutes = generateCacheRoutes(rowRoutes)
this.isInitAuthRoute = true
},
},
})