request.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. /**
  2. * H5版本的请求工具
  3. * 基于axios,兼容小程序的request接口
  4. * 依赖:common.js (提供公共工具函数)
  5. */
  6. // 环境配置
  7. const env = {
  8. baseUrl: 'https://m.hfdcschool.com'
  9. // baseUrl: 'https://yx.newfeifan.cn'
  10. }
  11. // Loading 管理器 (H5版本)
  12. const loadingManager = {
  13. loadingCount: 0,
  14. loadingTimer: null,
  15. loadingElement: null,
  16. // 显示 loading
  17. show(options = {}) {
  18. const config = {
  19. title: '加载中...',
  20. mask: true,
  21. delay: 300,
  22. ...options
  23. }
  24. // 如果已经有 loading 在显示,只增加计数
  25. if (this.loadingCount > 0) {
  26. this.loadingCount++
  27. return
  28. }
  29. // 延迟显示,避免快速请求造成闪烁
  30. this.loadingTimer = setTimeout(() => {
  31. if (this.loadingCount > 0) {
  32. this.createLoadingElement(config.title)
  33. }
  34. }, config.delay)
  35. this.loadingCount++
  36. },
  37. // 创建Loading元素
  38. createLoadingElement(title) {
  39. if (this.loadingElement) return
  40. this.loadingElement = document.createElement('div')
  41. this.loadingElement.className = 'h5-loading-mask'
  42. this.loadingElement.innerHTML = `
  43. <div class="h5-loading-content">
  44. <div class="h5-loading-spinner"></div>
  45. <div class="h5-loading-text">${title}</div>
  46. </div>
  47. `
  48. // 添加样式
  49. const style = document.createElement('style')
  50. style.textContent = `
  51. .h5-loading-mask {
  52. position: fixed;
  53. top: 0;
  54. left: 0;
  55. right: 0;
  56. bottom: 0;
  57. background: rgba(0, 0, 0, 0.5);
  58. display: flex;
  59. align-items: center;
  60. justify-content: center;
  61. z-index: 10000;
  62. }
  63. .h5-loading-content {
  64. background: white;
  65. padding: 20px;
  66. border-radius: 8px;
  67. text-align: center;
  68. min-width: 120px;
  69. }
  70. .h5-loading-spinner {
  71. width: 30px;
  72. height: 30px;
  73. border: 3px solid #f3f3f3;
  74. border-top: 3px solid #40ac6d;
  75. border-radius: 50%;
  76. animation: h5-spin 1s linear infinite;
  77. margin: 0 auto 10px;
  78. }
  79. @keyframes h5-spin {
  80. 0% { transform: rotate(0deg); }
  81. 100% { transform: rotate(360deg); }
  82. }
  83. .h5-loading-text {
  84. color: #333;
  85. font-size: 14px;
  86. }
  87. `
  88. document.head.appendChild(style)
  89. document.body.appendChild(this.loadingElement)
  90. },
  91. // 隐藏 loading
  92. hide() {
  93. this.loadingCount = Math.max(0, this.loadingCount - 1)
  94. if (this.loadingCount === 0) {
  95. // 清除延迟显示的定时器
  96. if (this.loadingTimer) {
  97. clearTimeout(this.loadingTimer)
  98. this.loadingTimer = null
  99. }
  100. // 移除 loading 元素
  101. if (this.loadingElement) {
  102. document.body.removeChild(this.loadingElement)
  103. this.loadingElement = null
  104. }
  105. }
  106. },
  107. // 强制隐藏所有 loading
  108. forceHide() {
  109. this.loadingCount = 0
  110. if (this.loadingTimer) {
  111. clearTimeout(this.loadingTimer)
  112. this.loadingTimer = null
  113. }
  114. if (this.loadingElement) {
  115. document.body.removeChild(this.loadingElement)
  116. this.loadingElement = null
  117. }
  118. }
  119. }
  120. // 注意:getUrlParams, getDeviceInfo, getJSessionId, saveJSessionId
  121. // 这些函数已在 common.js 中定义,这里直接使用全局函数
  122. const request = {
  123. async get(url, params = {}, options = {}) {
  124. return this.request(url, 'GET', params, options)
  125. },
  126. async post(url, data = {}, options = {}) {
  127. return this.request(url, 'POST', data, options)
  128. },
  129. async put(url, data = {}, options = {}) {
  130. return this.request(url, 'PUT', data, options)
  131. },
  132. async delete(url, data = {}, options = {}) {
  133. return this.request(url, 'DELETE', data, options)
  134. },
  135. async request(url, method, data, options = {}) {
  136. // 解析 loading 配置
  137. let loadingConfig
  138. if (options.loading === false) {
  139. loadingConfig = false
  140. } else {
  141. loadingConfig = {
  142. show: true,
  143. title: '加载中...',
  144. mask: true,
  145. delay: 300,
  146. timeout: 10000,
  147. ...(typeof options.loading === 'object' ? options.loading : {})
  148. }
  149. }
  150. // 解析请求配置
  151. const requestConfig = {
  152. timeout: 15000,
  153. ...options.request
  154. }
  155. const shouldShowLoading = loadingConfig !== false && loadingConfig.show !== false
  156. // 显示 loading
  157. if (shouldShowLoading) {
  158. loadingManager.show(loadingConfig)
  159. }
  160. // 获取设备信息
  161. const deviceInfo = getDeviceInfo()
  162. const devId = deviceInfo.deviceId || ''
  163. const sbmc = deviceInfo.model || ''
  164. // 处理URL,添加设备参数
  165. const separator = url.includes('?') ? '&' : '?'
  166. const finalUrl = `${url}${separator}devId=${devId}&sbmc=${sbmc}`
  167. // 超时处理
  168. let timeoutTimer = null
  169. if (shouldShowLoading && loadingConfig.timeout) {
  170. timeoutTimer = setTimeout(() => {
  171. loadingManager.hide()
  172. if (typeof showToastEffect !== 'undefined') {
  173. showToastEffect('请求超时', 3000, 'error')
  174. } else {
  175. // alert('请求超时')
  176. }
  177. }, loadingConfig.timeout)
  178. }
  179. try {
  180. // 配置axios请求
  181. const axiosConfig = {
  182. url: `${env.baseUrl}${finalUrl}`,
  183. method: method.toLowerCase(),
  184. timeout: requestConfig.timeout,
  185. headers: {}
  186. }
  187. // 处理请求数据
  188. if (method.toUpperCase() === 'GET') {
  189. axiosConfig.params = data
  190. } else {
  191. if (options.formData) {
  192. axiosConfig.headers['Content-Type'] = 'application/x-www-form-urlencoded'
  193. // 转换为表单格式
  194. const formData = new URLSearchParams()
  195. Object.keys(data).forEach(key => {
  196. formData.append(key, data[key])
  197. })
  198. axiosConfig.data = formData
  199. } else {
  200. axiosConfig.headers['Content-Type'] = 'application/json'
  201. axiosConfig.data = data
  202. }
  203. }
  204. // 发送请求
  205. const response = await axios(axiosConfig)
  206. // 清除超时定时器
  207. if (timeoutTimer) {
  208. clearTimeout(timeoutTimer)
  209. }
  210. // 检查服务器处理错误
  211. if (response.data && response.data.msg && response.data.msg.includes('页面执行时错误')) {
  212. throw new Error('服务器处理错误');
  213. }
  214. // 检查没有服务授权 - 直接回到小程序
  215. if (response.data && response.data.msg && response.data.msg.includes('没有服务授权')) {
  216. handleH5NoServiceAuth(response.data.msg);
  217. throw new Error(response.data.msg);
  218. }
  219. // 检查登录过期 - 根据实际响应体格式
  220. if (response && (
  221. response.data.errorcode === 1 ||
  222. response.data.msg === '登录已失效,请重新登录' ||
  223. response.data.message === '登录过期' ||
  224. response.data.error === 'UNAUTHORIZED'
  225. )) {
  226. console.log('H5检测到登录过期,触发自动登录', response);
  227. handleH5LoginExpired();
  228. throw new Error(response.msg || '登录过期');
  229. }
  230. // 返回与小程序兼容的格式
  231. return {
  232. data: response.data
  233. }
  234. } catch (error) {
  235. // 清除超时定时器
  236. if (timeoutTimer) {
  237. clearTimeout(timeoutTimer)
  238. }
  239. // 处理错误
  240. let errorMessage = '请求失败'
  241. if (error.response) {
  242. errorMessage = `请求失败: ${error.response.status}`
  243. } else if (error.request) {
  244. errorMessage = '网络连接失败'
  245. } else {
  246. errorMessage = error.message || '未知错误'
  247. }
  248. if (typeof showToastEffect !== 'undefined') {
  249. showToastEffect(errorMessage, 3000, 'error')
  250. } else {
  251. // alert(errorMessage)
  252. }
  253. throw error
  254. } finally {
  255. // 隐藏 loading
  256. if (shouldShowLoading) {
  257. loadingManager.hide()
  258. }
  259. }
  260. }
  261. }
  262. // H5登录过期处理
  263. const handleH5LoginExpired = () => {
  264. console.log('🔒 H5处理登录过期');
  265. // 获取yhsbToken,有token就自动登录,没有就跳转登录页
  266. const userInfo = localStorage.getItem('userInfo');
  267. let yhsbToken = '';
  268. if (userInfo) {
  269. try {
  270. const userData = JSON.parse(userInfo);
  271. yhsbToken = userData.yhsbToken;
  272. } catch (e) {
  273. console.error('解析用户信息失败:', e);
  274. }
  275. }
  276. if (yhsbToken) {
  277. // 直接调用自动登录接口(和自动登录页面一样的逻辑)
  278. request.post(
  279. `/service?ssServ=ss.login&wdConfirmationCaptchaService=0&mdToken=${yhsbToken}`,
  280. { mdToken: yhsbToken },
  281. { loading: false }
  282. ).then(response => {
  283. if (response && response.data) {
  284. console.log('✅ H5自动登录成功');
  285. // 构建用户数据(和自动登录页面一样)
  286. const userData = {
  287. devId: response.data.devId,
  288. sbmc: response.data.sbmc,
  289. sessId: response.data.sessId,
  290. userId: response.data.userId,
  291. xm: response.data.xm,
  292. yhsbToken: response.data.yhsbToken,
  293. onlineToken: response.data.onlineToken
  294. };
  295. // 保存用户信息到H5本地存储
  296. if (window.h5UserApi) {
  297. window.h5UserApi.saveUserInfo(userData);
  298. }
  299. // 通知小程序更新token
  300. if (typeof callNative === 'function') {
  301. callNative('loginSuccess', 'H5自动登录成功', {
  302. success: true,
  303. userInfo: userData,
  304. isAutoLogin: true
  305. });
  306. }
  307. // 刷新当前页面
  308. setTimeout(() => window.location.reload(), 1000);
  309. }
  310. }).catch(error => {
  311. console.error('❌ H5自动登录失败:', error);
  312. window.location.href = '/page/login.html?from=expired';
  313. });
  314. } else {
  315. console.log('⚠️ 未找到yhsbToken,跳转登录页面');
  316. window.location.href = '/page/login.html?from=expired';
  317. }
  318. };
  319. // H5没有服务授权处理
  320. const handleH5NoServiceAuth = (errorMsg) => {
  321. // 显示错误提示
  322. if (typeof showToastEffect !== 'undefined') {
  323. // showToastEffect('没有服务授权,即将返回', 2000, 'error');
  324. } else {
  325. }
  326. // 延迟一下让用户看到提示,然后返回小程序
  327. setTimeout(() => {
  328. // 通知小程序返回
  329. if (typeof callNative === 'function') {
  330. callNative('noServiceAuth', '没有服务授权', {
  331. error: true,
  332. message: errorMsg,
  333. action: 'goBack'
  334. });
  335. } else {
  336. // 降级处理:直接关闭页面
  337. if (window.history.length > 1) {
  338. window.history.back();
  339. } else {
  340. window.close();
  341. }
  342. }
  343. }, 1500);
  344. };
  345. // 导出到全局
  346. window.request = request
  347. window.handleH5LoginExpired = handleH5LoginExpired
  348. window.handleH5NoServiceAuth = handleH5NoServiceAuth
  349. console.log('✅ H5 Request工具已加载')