request.js 11 KB

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