request.js 11 KB

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