request.js 14 KB

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