fix(axios): 优化401未登录处理逻辑,仅在需要登录的路由跳转
仅在当前路由需要登录权限时才清除登录信息并重定向到登录页 公开页面(如课程详情)保持停留并由业务自行处理401结果
Showing
1 changed file
with
17 additions
and
7 deletions
| ... | @@ -2,12 +2,13 @@ | ... | @@ -2,12 +2,13 @@ |
| 2 | * @Author: hookehuyr hookehuyr@gmail.com | 2 | * @Author: hookehuyr hookehuyr@gmail.com |
| 3 | * @Date: 2022-05-28 10:17:40 | 3 | * @Date: 2022-05-28 10:17:40 |
| 4 | * @LastEditors: hookehuyr hookehuyr@gmail.com | 4 | * @LastEditors: hookehuyr hookehuyr@gmail.com |
| 5 | - * @LastEditTime: 2025-07-01 16:23:59 | 5 | + * @LastEditTime: 2025-12-04 14:06:16 |
| 6 | * @FilePath: /mlaj/src/utils/axios.js | 6 | * @FilePath: /mlaj/src/utils/axios.js |
| 7 | * @Description: | 7 | * @Description: |
| 8 | */ | 8 | */ |
| 9 | import axios from 'axios'; | 9 | import axios from 'axios'; |
| 10 | import router from '@/router'; | 10 | import router from '@/router'; |
| 11 | +import { checkAuth } from '@/router/guards' | ||
| 11 | // import qs from 'Qs' | 12 | // import qs from 'Qs' |
| 12 | // import { strExist } from '@/utils/tools' | 13 | // import { strExist } from '@/utils/tools' |
| 13 | 14 | ||
| ... | @@ -73,15 +74,24 @@ axios.interceptors.request.use( | ... | @@ -73,15 +74,24 @@ axios.interceptors.request.use( |
| 73 | */ | 74 | */ |
| 74 | axios.interceptors.response.use( | 75 | axios.interceptors.response.use( |
| 75 | response => { | 76 | response => { |
| 77 | + /** | ||
| 78 | + * @description 统一处理401未登录,仅在当前路由确实需要登录时才重定向 | ||
| 79 | + * - 公开页面(如课程详情)不再因为接口返回401而跳转登录 | ||
| 80 | + * - 仅当当前路由需要登录权限时,才清理登录信息并重定向到登录页 | ||
| 81 | + */ | ||
| 76 | if (response.data && response.data.code === 401) { | 82 | if (response.data && response.data.code === 401) { |
| 77 | - // 清除用户登录信息 | 83 | + const to = router.currentRoute.value; |
| 84 | + const auth_check_result = checkAuth(to); | ||
| 85 | + const need_login_redirect = auth_check_result !== true; | ||
| 86 | + | ||
| 87 | + if (need_login_redirect) { | ||
| 88 | + // 仅在受限页面触发登录重定向 | ||
| 78 | localStorage.removeItem('currentUser'); | 89 | localStorage.removeItem('currentUser'); |
| 79 | - // 清除认证请求头 | ||
| 80 | clearAuthHeaders(); | 90 | clearAuthHeaders(); |
| 81 | - // 跳转到登录页面,并携带当前路由信息 | 91 | + const current_path = to.fullPath; |
| 82 | - const currentPath = router.currentRoute.value.fullPath; | 92 | + router.push(`/login?redirect=${encodeURIComponent(current_path)}`); |
| 83 | - router.push(`/login?redirect=${encodeURIComponent(currentPath)}`); | 93 | + } |
| 84 | - // router.push(`/login`); | 94 | + // 对公开页面,保持页面停留并由业务自行处理401结果 |
| 85 | } | 95 | } |
| 86 | return response; | 96 | return response; |
| 87 | }, | 97 | }, | ... | ... |
-
Please register or login to post a comment