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 VITE_COPYRIGHT_INFO = Copyright © 2024 chansee97
# 自动刷新token # 自动刷新token
VITE_AUTO_REFRESH_TOKEN = Y VITE_AUTO_REFRESH_TOKEN = N
# 默认多语言 enUS | zhCN # 默认多语言 enUS | zhCN
VITE_DEFAULT_LANG = enUS VITE_DEFAULT_LANG = enUS

View File

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

View File

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

View File

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

View File

@ -39,23 +39,22 @@ export const useRouteStore = defineStore('route-store', {
async initRouteInfo() { async initRouteInfo() {
if (import.meta.env.VITE_ROUTE_LOAD_MODE === 'dynamic') { 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) { if (!result.isSuccess || !result.data) {
const authStore = useAuthStore() throw new Error('Failed to fetch user routes')
authStore.logout() }
return
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 { else {
this.rowRoutes = staticRoutes this.rowRoutes = staticRoutes
@ -65,25 +64,33 @@ export const useRouteStore = defineStore('route-store', {
async initAuthRoute() { async initAuthRoute() {
this.isInitAuthRoute = false this.isInitAuthRoute = false
// Initialize route information try {
const rowRoutes = await this.initRouteInfo() // Initialize route information
if (!rowRoutes) { const rowRoutes = await this.initRouteInfo()
window.$message.error($t(`app.getRouteError`)) if (!rowRoutes) {
return 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
}, },
}, },
}) })