request.js
6.46 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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
/*
* @Date: 2022-09-19 14:11:06
* @LastEditors: hookehuyr hookehuyr@gmail.com
* @LastEditTime: 2025-09-20 11:18:35
* @FilePath: /lls_program/src/utils/request.js
* @Description: 简单axios封装,后续按实际处理
*/
// import axios from 'axios'
import axios from 'axios-miniprogram';
// // import qs from 'Qs'
import { silentAuth } from '@/utils/authRedirect'
import Taro from '@tarojs/taro';
// import { ProgressStart, ProgressEnd } from '@/components/axios-progress/progress';
// import store from '@/store'
// import { getToken } from '@/utils/auth'
import BASE_URL from './config';
/**
* 获取sessionid的工具函数
* @returns {string|null} sessionid或null
*/
const getSessionId = () => {
try {
return wx.getStorageSync("sessionid") || null;
} catch (error) {
console.error('获取sessionid失败:', error);
return null;
}
};
/**
* 设置sessionid的工具函数
* @param {string} sessionid - 要设置的sessionid
*/
const setSessionId = (sessionid) => {
try {
wx.setStorageSync("sessionid", sessionid);
} catch (error) {
console.error('设置sessionid失败:', error);
}
};
/**
* 清除sessionid的工具函数
*/
const clearSessionId = () => {
try {
wx.removeStorageSync("sessionid");
} catch (error) {
console.error('清除sessionid失败:', error);
}
};
// create an axios instance
const service = axios.create({
baseURL: BASE_URL, // url = base url + request url
// withCredentials: true, // send cookies when cross-domain requests
timeout: 5000, // request timeout
})
service.defaults.params = {
f: 'walk',
};
// request interceptor
service.interceptors.request.use(
config => {
// console.warn(config)
// console.warn(store)
/**
* 动态获取sessionid并设置到请求头
* 确保每个请求都带上最新的sessionid
*/
const sessionid = getSessionId();
if (sessionid) {
config.headers.cookie = sessionid;
}
/**
* POST PHP需要修改数据格式
* 序列化POST请求时需要屏蔽上传相关接口,上传相关接口序列化后报错
*/
// config.data = config.method === 'post' && !strExist(['a=upload', 'upload.qiniup.com'], config.url) ? qs.stringify(config.data) : config.data;
return config
},
error => {
// do something with request error
console.error(error, 'err') // for debug
return Promise.reject(error)
}
)
// response interceptor
service.interceptors.response.use(
/**
* If you want to get http information such as headers or status
* Please return response => response
*/
/**
* Determine the request status by custom code
* Here is just an example
* You can also judge the status by HTTP Status Code
*/
response => {
/**
* 检查响应头中是否有新的sessionid
* 如果有,则更新本地存储
*/
const setCookieHeader = response.headers['set-cookie'];
if (setCookieHeader) {
// 解析set-cookie头,提取sessionid
const sessionidMatch = setCookieHeader.match(/sessionid=([^;]+)/);
if (sessionidMatch && sessionidMatch[1]) {
setSessionId(sessionidMatch[1]);
}
}
// wx.hideLoading();
// const res = response.data
// // Toast.clear();
// // if the custom code is not 20000, it is judged as an error.
// if (res.code !== 100000) {
// // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
// if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
// // to re-login
// // Toast.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
// // confirmButtonText: 'Re-Login',
// // cancelButtonText: 'Cancel',
// // type: 'warning'
// // }).then(() => {
// // // store.dispatch('user/resetToken').then(() => {
// // // location.reload()
// // // })
// // })
// } else {
// // Toast.fail({
// // message: res.message,
// // duration: 1.5 * 1000
// // })
// // Tips.error(res.message, false)
// }
// return Promise.reject(new Error(res.message || 'Error'))
// } else {
// return res
// }
/**
* 处理401未授权状态
* 清除本地sessionid并使用静默授权
*/
if (response.data.code === 401) {
// 清除无效的sessionid
clearSessionId();
// 检查当前页面,避免在Welcome页面重复跳转
let currentRoute = '';
try {
const pages = getCurrentPages();
if (pages && pages.length > 0) {
const currentPage = pages[pages.length - 1];
currentRoute = currentPage.route || '';
}
} catch (error) {
console.error('获取当前页面路由失败:', error);
}
// 使用静默授权处理,但避免重复跳转
return silentAuth(
() => {
// 授权成功后重新发起原始请求
const originalRequest = response.config;
return service.request(originalRequest).then(retryResponse => {
// 检查是否是微信步数同步请求
if (originalRequest.url && originalRequest.url.includes('sync_wx_step')) {
// 如果是步数同步请求且成功,触发全局事件
if (retryResponse.data && retryResponse.data.code == 1) {
// 使用Taro的事件系统触发全局事件
if (typeof Taro !== 'undefined' && Taro.eventCenter) {
Taro.eventCenter.trigger('wx-steps-sync-success');
}
}
}
return retryResponse;
});
},
() => {
// 静默授权失败,直接返回错误,不跳转页面
return Promise.reject(new Error('授权失败,请稍后重试'));
},
// 传入当前路由,避免重复跳转到Welcome页面
currentRoute === 'pages/Welcome/index'
).catch(() => {
// 如果静默授权完全失败,直接返回错误,不跳转页面
return Promise.reject(new Error('授权失败,请稍后重试'));
});
}
return response
},
error => {
// Toast.clear();
console.error('err' + error) // for debug
// Toast.fail({
// message: error.message,
// duration: 1.5 * 1000
// })
return Promise.reject(error)
}
)
// 导出sessionid管理工具函数
export { getSessionId, setSessionId, clearSessionId };
export default service