request.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  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. // 功能说明:H5 请求超时统一调到 1 分钟,避免审核/变动类慢接口过早超时 by xu 2026-03-09
  142. loadingConfig = {
  143. show: true,
  144. title: "加载中...",
  145. mask: true,
  146. delay: 300,
  147. timeout: 60000,
  148. ...(typeof options.loading === "object" ? options.loading : {}),
  149. };
  150. }
  151. // 解析请求配置
  152. // 功能说明:H5 axios 请求超时统一调到 1 分钟,和 loading 超时提示保持一致 by xu 2026-03-09
  153. const requestConfig = {
  154. timeout: 60000,
  155. ...options.request,
  156. };
  157. const shouldShowLoading =
  158. loadingConfig !== false && loadingConfig.show !== false;
  159. // 显示 loading
  160. if (shouldShowLoading) {
  161. loadingManager.show(loadingConfig);
  162. }
  163. // 获取设备信息
  164. const deviceInfo = getDeviceInfo();
  165. const devId = deviceInfo.deviceId || "";
  166. const sbmc = deviceInfo.model || "";
  167. // 处理URL,添加设备参数
  168. const separator = url.includes("?") ? "&" : "?";
  169. const finalUrl = `${url}${separator}devId=${devId}&sbmc=${sbmc}`;
  170. // 超时处理
  171. let timeoutTimer = null;
  172. if (shouldShowLoading && loadingConfig.timeout) {
  173. timeoutTimer = setTimeout(() => {
  174. loadingManager.hide();
  175. if (typeof showToastEffect !== "undefined") {
  176. showToastEffect("请求超时", 3000, "error");
  177. } else {
  178. // alert('请求超时')
  179. }
  180. }, loadingConfig.timeout);
  181. }
  182. try {
  183. // 配置axios请求
  184. const axiosConfig = {
  185. url: `${env.baseUrl}${finalUrl}`,
  186. method: method.toLowerCase(),
  187. timeout: requestConfig.timeout,
  188. headers: {},
  189. };
  190. // 处理请求数据
  191. if (method.toUpperCase() === "GET") {
  192. axiosConfig.params = data;
  193. } else {
  194. if (options.formData) {
  195. axiosConfig.headers["Content-Type"] =
  196. "application/x-www-form-urlencoded";
  197. // 转换为表单格式
  198. const formData = new URLSearchParams();
  199. Object.keys(data).forEach((key) => {
  200. const value = data[key];
  201. // 如果是数组,为每个元素单独添加参数(同名参数重复)
  202. if (Array.isArray(value)) {
  203. value.forEach((item) => {
  204. formData.append(key, item);
  205. });
  206. } else {
  207. formData.append(key, value);
  208. }
  209. });
  210. axiosConfig.data = formData;
  211. } else {
  212. axiosConfig.headers["Content-Type"] = "application/json";
  213. axiosConfig.data = data;
  214. }
  215. }
  216. // 发送请求
  217. const response = await axios(axiosConfig);
  218. // 清除超时定时器
  219. if (timeoutTimer) {
  220. clearTimeout(timeoutTimer);
  221. }
  222. // 检查服务器处理错误
  223. if (
  224. response.data &&
  225. response.data.msg &&
  226. response.data.msg.includes("页面执行时错误")
  227. ) {
  228. throw new Error("服务器处理错误");
  229. }
  230. // 检查没有服务授权 - 直接回到小程序
  231. if (
  232. response.data &&
  233. response.data.msg &&
  234. response.data.msg.includes("没有服务授权")
  235. ) {
  236. handleH5NoServiceAuth(response.data.msg);
  237. throw new Error(response.data.msg);
  238. }
  239. // 检查登录过期 - 根据实际响应体格式
  240. if (
  241. response &&
  242. (response.data.errorcode === 1 ||
  243. response.data.msg === "登录已失效,请重新登录" ||
  244. response.data.message === "登录过期" ||
  245. response.data.error === "UNAUTHORIZED")
  246. ) {
  247. console.log("H5检测到登录过期,触发自动登录", response);
  248. handleH5LoginExpired();
  249. throw new Error(response.msg || "登录过期");
  250. }
  251. // 返回与小程序兼容的格式
  252. return {
  253. data: response.data,
  254. };
  255. } catch (error) {
  256. // 清除超时定时器
  257. if (timeoutTimer) {
  258. clearTimeout(timeoutTimer);
  259. }
  260. // 处理错误
  261. let errorMessage = "请求失败";
  262. if (error.response) {
  263. errorMessage = `请求失败: ${error.response.status}`;
  264. } else if (error.request) {
  265. errorMessage = "网络连接失败";
  266. } else {
  267. errorMessage = error.message || "未知错误";
  268. }
  269. if (typeof showToastEffect !== "undefined") {
  270. showToastEffect(errorMessage, 3000, "error");
  271. } else {
  272. // alert(errorMessage)
  273. }
  274. throw error;
  275. } finally {
  276. // 隐藏 loading
  277. if (shouldShowLoading) {
  278. loadingManager.hide();
  279. }
  280. }
  281. },
  282. };
  283. // H5登录过期处理
  284. const handleH5LoginExpired = () => {
  285. console.log("🔒 H5处理登录过期");
  286. // 获取yhsbToken,有token就自动登录,没有就跳转登录页
  287. const userInfo = localStorage.getItem("userInfo");
  288. let yhsbToken = "";
  289. if (userInfo) {
  290. try {
  291. const userData = JSON.parse(userInfo);
  292. yhsbToken = userData.yhsbToken;
  293. } catch (e) {
  294. console.error("解析用户信息失败:", e);
  295. }
  296. }
  297. if (yhsbToken) {
  298. // 直接调用自动登录接口(和自动登录页面一样的逻辑)
  299. request
  300. .post(
  301. `/service?ssServ=ssLogin&wdConfirmationCaptchaService=0&mdToken=${yhsbToken}`,
  302. { mdToken: yhsbToken },
  303. { loading: false }
  304. )
  305. .then((response) => {
  306. if (response && response.data) {
  307. console.log("✅ H5自动登录成功");
  308. // 构建用户数据(和自动登录页面一样)
  309. const userData = {
  310. devId: response.data.devId,
  311. sbmc: response.data.sbmc,
  312. sessId: response.data.sessId,
  313. userId: response.data.userId,
  314. xm: response.data.xm,
  315. yhsbToken: response.data.yhsbToken,
  316. onlineToken: response.data.onlineToken,
  317. };
  318. // 保存用户信息到H5本地存储
  319. if (window.h5UserApi) {
  320. window.h5UserApi.saveUserInfo(userData);
  321. }
  322. // 通知小程序更新token
  323. if (typeof callNative === "function") {
  324. callNative("loginSuccess", "H5自动登录成功", {
  325. success: true,
  326. userInfo: userData,
  327. isAutoLogin: true,
  328. });
  329. }
  330. // 刷新当前页面
  331. setTimeout(() => window.location.reload(), 1000);
  332. }
  333. })
  334. .catch((error) => {
  335. console.error("❌ H5自动登录失败:", error);
  336. window.location.href = "/page/login.html?from=expired";
  337. });
  338. } else {
  339. console.log("⚠️ 未找到yhsbToken,跳转登录页面");
  340. window.location.href = "/page/login.html?from=expired";
  341. }
  342. };
  343. // H5没有服务授权处理
  344. const handleH5NoServiceAuth = (errorMsg) => {
  345. // 显示错误提示
  346. if (typeof showToastEffect !== "undefined") {
  347. // showToastEffect('没有服务授权,即将返回', 2000, 'error');
  348. } else {
  349. }
  350. // 延迟一下让用户看到提示,然后返回小程序
  351. setTimeout(() => {
  352. // 通知小程序返回
  353. if (typeof callNative === "function") {
  354. callNative("noServiceAuth", "没有服务授权", {
  355. error: true,
  356. message: errorMsg,
  357. action: "goBack",
  358. });
  359. } else {
  360. // 降级处理:直接关闭页面
  361. if (window.history.length > 1) {
  362. window.history.back();
  363. } else {
  364. window.close();
  365. }
  366. }
  367. }, 1500);
  368. };
  369. // 导出到全局
  370. window.request = request;
  371. window.handleH5LoginExpired = handleH5LoginExpired;
  372. window.handleH5NoServiceAuth = handleH5NoServiceAuth;
  373. console.log("✅ H5 Request工具已加载");