request.js 12 KB

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