hookehuyr

refactor(router): 优化认证检查逻辑,减少冗余代码

将用户信息获取逻辑移至需要认证的路由检查之后,避免不必要的接口请求
...@@ -56,21 +56,6 @@ export const checkWxAuth = async () => { ...@@ -56,21 +56,6 @@ export const checkWxAuth = async () => {
56 56
57 // 登录权限检查 57 // 登录权限检查
58 export const checkAuth = async (to) => { 58 export const checkAuth = async (to) => {
59 - try {
60 - // 先请求用户信息接口
61 - const { code, data } = await getUserInfoAPI()
62 - if (code) {
63 - // 如果成功获取用户信息,更新currentUser并允许访问
64 - localStorage.setItem('currentUser', JSON.stringify(data))
65 - return true
66 - }
67 - } catch (error) {
68 - console.error('获取用户信息失败:', error)
69 - }
70 -
71 - // 如果接口请求失败或返回401,继续原有的本地存储判断逻辑
72 - const currentUser = JSON.parse(localStorage.getItem('currentUser'))
73 -
74 // 检查当前路由是否需要认证 59 // 检查当前路由是否需要认证
75 const needAuth = authRequiredRoutes.some((route) => { 60 const needAuth = authRequiredRoutes.some((route) => {
76 // 如果是正则匹配模式 61 // 如果是正则匹配模式
...@@ -85,8 +70,21 @@ export const checkAuth = async (to) => { ...@@ -85,8 +70,21 @@ export const checkAuth = async (to) => {
85 return to.path.startsWith(route.path) 70 return to.path.startsWith(route.path)
86 }) 71 })
87 72
88 - if (needAuth && !currentUser) { 73 + // 如果路由需要认证,则尝试获取用户信息
89 - // 未登录时重定向到登录页面 74 + if (needAuth) {
75 + try {
76 + // 请求用户信息接口
77 + const { code, data } = await getUserInfoAPI()
78 + if (code) {
79 + // 如果成功获取用户信息,更新currentUser并允许访问
80 + localStorage.setItem('currentUser', JSON.stringify(data))
81 + return true
82 + }
83 + } catch (error) {
84 + console.error('获取用户信息失败:', error)
85 + }
86 +
87 + // 如果接口请求失败或返回401,直接重定向到登录页面
90 return { path: '/login', query: { redirect: to.fullPath } } 88 return { path: '/login', query: { redirect: to.fullPath } }
91 } 89 }
92 90
......