request.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  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. // 发送请求
  219. const response = await axios(axiosConfig);
  220. // 清除超时定时器
  221. if (timeoutTimer) {
  222. clearTimeout(timeoutTimer);
  223. }
  224. // 检查服务器处理错误
  225. if (
  226. response.data &&
  227. response.data.msg &&
  228. response.data.msg.includes("页面执行时错误")
  229. ) {
  230. throw new Error("服务器处理错误");
  231. }
  232. // 检查没有服务授权 - 直接回到小程序
  233. if (
  234. response.data &&
  235. response.data.msg &&
  236. response.data.msg.includes("没有服务授权")
  237. ) {
  238. handleH5NoServiceAuth(response.data.msg);
  239. throw new Error(response.data.msg);
  240. }
  241. // 检查登录过期 - 根据实际响应体格式
  242. if (
  243. response &&
  244. (response.data.errorcode === 1 ||
  245. response.data.msg === "登录已失效,请重新登录" ||
  246. response.data.message === "登录过期" ||
  247. response.data.error === "UNAUTHORIZED")
  248. ) {
  249. console.log("H5检测到登录过期,触发自动登录", response);
  250. handleH5LoginExpired();
  251. throw new Error(response.msg || "登录过期");
  252. }
  253. // 返回与小程序兼容的格式
  254. return {
  255. data: response.data,
  256. };
  257. } catch (error) {
  258. // 清除超时定时器
  259. if (timeoutTimer) {
  260. clearTimeout(timeoutTimer);
  261. }
  262. // 处理错误
  263. let errorMessage = "请求失败";
  264. if (error.response) {
  265. errorMessage = `请求失败: ${error.response.status}`;
  266. } else if (error.request) {
  267. errorMessage = "网络连接失败";
  268. } else {
  269. errorMessage = error.message || "未知错误";
  270. }
  271. if (typeof showToastEffect !== "undefined") {
  272. showToastEffect(errorMessage, 3000, "error");
  273. } else {
  274. // alert(errorMessage)
  275. }
  276. throw error;
  277. } finally {
  278. // 隐藏 loading
  279. if (shouldShowLoading) {
  280. loadingManager.hide();
  281. }
  282. }
  283. },
  284. };
  285. // H5登录过期处理
  286. const handleH5LoginExpired = () => {
  287. console.log("🔒 H5处理登录过期");
  288. // 获取yhsbToken,有token就自动登录,没有就跳转登录页
  289. const userInfo = localStorage.getItem("userInfo");
  290. let yhsbToken = "";
  291. if (userInfo) {
  292. try {
  293. const userData = JSON.parse(userInfo);
  294. yhsbToken = userData.yhsbToken;
  295. } catch (e) {
  296. console.error("解析用户信息失败:", e);
  297. }
  298. }
  299. if (yhsbToken) {
  300. // 直接调用自动登录接口(和自动登录页面一样的逻辑)
  301. request
  302. .post(
  303. `/service?ssServ=ssLogin&wdConfirmationCaptchaService=0&mdToken=${yhsbToken}`,
  304. { mdToken: yhsbToken },
  305. { loading: false }
  306. )
  307. .then((response) => {
  308. if (response && response.data) {
  309. console.log("✅ H5自动登录成功");
  310. // 构建用户数据(和自动登录页面一样)
  311. const userData = {
  312. devId: response.data.devId,
  313. sbmc: response.data.sbmc,
  314. sessId: response.data.sessId,
  315. userId: response.data.userId,
  316. xm: response.data.xm,
  317. yhsbToken: response.data.yhsbToken,
  318. onlineToken: response.data.onlineToken,
  319. };
  320. // 保存用户信息到H5本地存储
  321. if (window.h5UserApi) {
  322. window.h5UserApi.saveUserInfo(userData);
  323. }
  324. // 通知小程序更新token
  325. if (typeof callNative === "function") {
  326. callNative("loginSuccess", "H5自动登录成功", {
  327. success: true,
  328. userInfo: userData,
  329. isAutoLogin: true,
  330. });
  331. }
  332. // 刷新当前页面
  333. setTimeout(() => window.location.reload(), 1000);
  334. }
  335. })
  336. .catch((error) => {
  337. console.error("❌ H5自动登录失败:", error);
  338. window.location.href = "/page/login.html?from=expired";
  339. });
  340. } else {
  341. console.log("⚠️ 未找到yhsbToken,跳转登录页面");
  342. window.location.href = "/page/login.html?from=expired";
  343. }
  344. };
  345. // H5没有服务授权处理
  346. const handleH5NoServiceAuth = (errorMsg) => {
  347. // 显示错误提示
  348. if (typeof showToastEffect !== "undefined") {
  349. // showToastEffect('没有服务授权,即将返回', 2000, 'error');
  350. } else {
  351. }
  352. // 延迟一下让用户看到提示,然后返回小程序
  353. setTimeout(() => {
  354. // 通知小程序返回
  355. if (typeof callNative === "function") {
  356. callNative("noServiceAuth", "没有服务授权", {
  357. error: true,
  358. message: errorMsg,
  359. action: "goBack",
  360. });
  361. } else {
  362. // 降级处理:直接关闭页面
  363. if (window.history.length > 1) {
  364. window.history.back();
  365. } else {
  366. window.close();
  367. }
  368. }
  369. }, 1500);
  370. };
  371. // 导出到全局
  372. window.request = request;
  373. window.handleH5LoginExpired = handleH5LoginExpired;
  374. window.handleH5NoServiceAuth = handleH5NoServiceAuth;
  375. console.log("✅ H5 Request工具已加载");