hookehuyr

fix(axios): 优化401未登录处理逻辑,仅在需要登录的路由跳转

仅在当前路由需要登录权限时才清除登录信息并重定向到登录页
公开页面(如课程详情)保持停留并由业务自行处理401结果
......@@ -2,12 +2,13 @@
* @Author: hookehuyr hookehuyr@gmail.com
* @Date: 2022-05-28 10:17:40
* @LastEditors: hookehuyr hookehuyr@gmail.com
* @LastEditTime: 2025-07-01 16:23:59
* @LastEditTime: 2025-12-04 14:06:16
* @FilePath: /mlaj/src/utils/axios.js
* @Description:
*/
import axios from 'axios';
import router from '@/router';
import { checkAuth } from '@/router/guards'
// import qs from 'Qs'
// import { strExist } from '@/utils/tools'
......@@ -73,15 +74,24 @@ axios.interceptors.request.use(
*/
axios.interceptors.response.use(
response => {
/**
* @description 统一处理401未登录,仅在当前路由确实需要登录时才重定向
* - 公开页面(如课程详情)不再因为接口返回401而跳转登录
* - 仅当当前路由需要登录权限时,才清理登录信息并重定向到登录页
*/
if (response.data && response.data.code === 401) {
// 清除用户登录信息
const to = router.currentRoute.value;
const auth_check_result = checkAuth(to);
const need_login_redirect = auth_check_result !== true;
if (need_login_redirect) {
// 仅在受限页面触发登录重定向
localStorage.removeItem('currentUser');
// 清除认证请求头
clearAuthHeaders();
// 跳转到登录页面,并携带当前路由信息
const currentPath = router.currentRoute.value.fullPath;
router.push(`/login?redirect=${encodeURIComponent(currentPath)}`);
// router.push(`/login`);
const current_path = to.fullPath;
router.push(`/login?redirect=${encodeURIComponent(current_path)}`);
}
// 对公开页面,保持页面停留并由业务自行处理401结果
}
return response;
},
......