hookehuyr

fix(axios): 添加401响应处理以跳转登录页

在axios拦截器中添加对401响应的处理,清除用户登录信息并跳转到登录页,同时携带当前路由信息以便登录后重定向
...@@ -2,12 +2,12 @@ ...@@ -2,12 +2,12 @@
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-03-25 15:03:55 5 + * @LastEditTime: 2025-05-08 17:45:44
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 qs from 'Qs' 11 // import qs from 'Qs'
12 // import { strExist } from '@/utils/tools' 12 // import { strExist } from '@/utils/tools'
13 13
...@@ -43,9 +43,17 @@ axios.interceptors.request.use( ...@@ -43,9 +43,17 @@ axios.interceptors.request.use(
43 */ 43 */
44 axios.interceptors.response.use( 44 axios.interceptors.response.use(
45 response => { 45 response => {
46 + if (response.data && response.data.code === 401) {
47 + // 清除用户登录信息
48 + localStorage.removeItem('currentUser');
49 + // 跳转到登录页面,并携带当前路由信息
50 + const currentPath = router.currentRoute.value.fullPath;
51 + router.push(`/login?redirect=${encodeURIComponent(currentPath)}`);
52 + }
46 return response; 53 return response;
47 }, 54 },
48 error => { 55 error => {
56 + // 响应错误处理
49 return Promise.reject(error); 57 return Promise.reject(error);
50 }); 58 });
51 59
......