Toggle navigation
Toggle navigation
This project
Loading...
Sign in
Hooke
/
mlaj
Go to a project
Toggle navigation
Toggle navigation pinning
Projects
Groups
Snippets
Help
Project
Activity
Repository
Pipelines
Graphs
Issues
0
Merge Requests
0
Wiki
Snippets
Network
Create a new issue
Builds
Commits
Issue Boards
Authored by
hookehuyr
2025-03-26 10:13:09 +0800
Browse Files
Options
Browse Files
Download
Email Patches
Plain Diff
Commit
ef7dc9b6c7f64d2abb63d9706780e455395c1451
ef7dc9b6
1 parent
2bb1ae97
refactor(router): 优化认证检查逻辑,减少冗余代码
将用户信息获取逻辑移至需要认证的路由检查之后,避免不必要的接口请求
Hide whitespace changes
Inline
Side-by-side
Showing
1 changed file
with
15 additions
and
17 deletions
src/router/guards.js
src/router/guards.js
View file @
ef7dc9b
...
...
@@ -56,21 +56,6 @@ export const checkWxAuth = async () => {
// 登录权限检查
export
const
checkAuth
=
async
(
to
)
=>
{
try
{
// 先请求用户信息接口
const
{
code
,
data
}
=
await
getUserInfoAPI
()
if
(
code
)
{
// 如果成功获取用户信息,更新currentUser并允许访问
localStorage
.
setItem
(
'currentUser'
,
JSON
.
stringify
(
data
))
return
true
}
}
catch
(
error
)
{
console
.
error
(
'获取用户信息失败:'
,
error
)
}
// 如果接口请求失败或返回401,继续原有的本地存储判断逻辑
const
currentUser
=
JSON
.
parse
(
localStorage
.
getItem
(
'currentUser'
))
// 检查当前路由是否需要认证
const
needAuth
=
authRequiredRoutes
.
some
((
route
)
=>
{
// 如果是正则匹配模式
...
...
@@ -85,8 +70,21 @@ export const checkAuth = async (to) => {
return to.path.startsWith(route.path)
})
if (needAuth && !currentUser) {
// 未登录时重定向到登录页面
// 如果路由需要认证,则尝试获取用户信息
if (needAuth) {
try {
// 请求用户信息接口
const { code, data } = await getUserInfoAPI()
if (code) {
// 如果成功获取用户信息,更新currentUser并允许访问
localStorage.setItem('currentUser', JSON.stringify(data))
return true
}
} catch (error) {
console.error('获取用户信息失败:', error)
}
// 如果接口请求失败或返回401,直接重定向到登录页面
return { path: '/login', query: { redirect: to.fullPath } }
}
...
...
Please
register
or
login
to post a comment