axios.js
3.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
/*
* @Author: hookehuyr hookehuyr@gmail.com
* @Date: 2022-05-28 10:17:40
* @LastEditors: hookehuyr hookehuyr@gmail.com
* @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'
// axios.defaults.baseURL = 'http://localhost:3000/api';
axios.defaults.params = {
f: 'behalo',
};
/**
* 设置用户认证信息到请求头
* @param {string} userId - 用户ID
* @param {string} userToken - 用户Token
*/
export const setAuthHeaders = (userId, userToken) => {
if (userId && userToken) {
axios.defaults.headers['User-Id'] = userId;
axios.defaults.headers['User-Token'] = userToken;
}
};
/**
* 清除用户认证信息
*/
export const clearAuthHeaders = () => {
delete axios.defaults.headers['User-Id'];
delete axios.defaults.headers['User-Token'];
};
/**
* @description 请求拦截器
*/
axios.interceptors.request.use(
config => {
/**
* 司总授权信息
* 动态获取 user_info 并设置到请求头
* 确保每个请求都带上最新的 user_info
*/
const user_info = localStorage.getItem('user_info') ? JSON.parse(localStorage.getItem('user_info')) : {};
if (user_info) {
config.headers['User-Id'] = user_info.user_id;
config.headers['User-Token'] = user_info.HTTP_USER_TOKEN;
}
// const url_params = parseQueryString(location.href);
// GET请求默认打上时间戳,避免从缓存中拿数据。
const timestamp = config.method === 'get' ? (new Date()).valueOf() : '';
/**
* POST PHP需要修改数据格式
* 序列化POST请求时需要屏蔽上传相关接口,上传相关接口序列化后报错
*/
// config.data = config.method === 'post' && !strExist(['a=upload', 'upload.qiniup.com'], config.url) ? qs.stringify(config.data) : config.data;
// 绑定默认请求头
config.params = { ...config.params, timestamp }
return config;
},
error => {
// 请求错误处理
return Promise.reject(error);
});
/**
* @description 响应拦截器
*/
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 current_path = to.fullPath;
router.push(`/login?redirect=${encodeURIComponent(current_path)}`);
}
// 对公开页面,保持页面停留并由业务自行处理401结果
}
return response;
},
error => {
// 响应错误处理
return Promise.reject(error);
});
export default axios;