request.js 12 KB

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