| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501 |
- /**
- * H5版本的请求工具
- * 基于axios,兼容小程序的request接口
- * 依赖:common.js (提供公共工具函数)
- */
- // 环境配置
- const env = {
- // 自动获取当前域名作为API地址,兜底使用 m.hfdcschool.com
- baseUrl:
- window.location.protocol + "//" + window.location.host ||
- "https://m.hfdcschool.com",
- };
- const getSessionIdFromResponseData = (data) => {
- if (!data || typeof data !== "object") {
- return "";
- }
- return data.sessId || data.JSESSIONID || data.jsessionId || "";
- };
- const isLoginExpiredResponseData = (data) => {
- if (!data || typeof data !== "object") {
- return false;
- }
- const message = String(data.msg || data.message || data.ssMsg || "");
- return (
- Number(data.errorcode) === 1 ||
- data.error === "UNAUTHORIZED" ||
- /登录(状态)?已失效|登录已过期|登录过期/.test(message)
- );
- };
- const isLoginExpiredHttpError = (error) => {
- const status = Number(error?.response?.status || 0);
- return status === 401 || isLoginExpiredResponseData(error?.response?.data);
- };
- let manualLoginRedirecting = false;
- const redirectToManualLogin = () => {
- if (manualLoginRedirecting) {
- return;
- }
- manualLoginRedirecting = true;
- const params = new URLSearchParams(window.location.search);
- params.delete("yhsbToken");
- params.delete("onlineToken");
- params.delete("mdToken");
- params.delete("JSESSIONID");
- params.set("from", "expired");
- window.setTimeout(() => {
- window.location.href = `/page/login.html?${params.toString()}`;
- }, 300);
- };
- // Loading 管理器 (H5版本)
- const loadingManager = {
- loadingCount: 0,
- loadingTimer: null,
- loadingElement: null,
- // 显示 loading
- show(options = {}) {
- const config = {
- title: "加载中...",
- mask: true,
- delay: 300,
- ...options,
- };
- // 如果已经有 loading 在显示,只增加计数
- if (this.loadingCount > 0) {
- this.loadingCount++;
- return;
- }
- // 延迟显示,避免快速请求造成闪烁
- this.loadingTimer = setTimeout(() => {
- if (this.loadingCount > 0) {
- this.createLoadingElement(config.title);
- }
- }, config.delay);
- this.loadingCount++;
- },
- // 创建Loading元素
- createLoadingElement(title) {
- if (this.loadingElement) return;
- this.loadingElement = document.createElement("div");
- this.loadingElement.className = "h5-loading-mask";
- this.loadingElement.innerHTML = `
- <div class="h5-loading-content">
- <div class="h5-loading-spinner"></div>
- <div class="h5-loading-text">${title}</div>
- </div>
- `;
- // 添加样式
- const style = document.createElement("style");
- style.textContent = `
- .h5-loading-mask {
- position: fixed;
- top: 0;
- left: 0;
- right: 0;
- bottom: 0;
- background: rgba(0, 0, 0, 0.5);
- display: flex;
- align-items: center;
- justify-content: center;
- z-index: 10000;
- }
- .h5-loading-content {
- background: white;
- padding: 20px;
- border-radius: 8px;
- text-align: center;
- min-width: 120px;
- }
- .h5-loading-spinner {
- width: 30px;
- height: 30px;
- border: 3px solid #f3f3f3;
- border-top: 3px solid #40ac6d;
- border-radius: 50%;
- animation: h5-spin 1s linear infinite;
- margin: 0 auto 10px;
- }
- @keyframes h5-spin {
- 0% { transform: rotate(0deg); }
- 100% { transform: rotate(360deg); }
- }
- .h5-loading-text {
- color: #333;
- font-size: 14px;
- }
- `;
- document.head.appendChild(style);
- document.body.appendChild(this.loadingElement);
- },
- // 隐藏 loading
- hide() {
- this.loadingCount = Math.max(0, this.loadingCount - 1);
- if (this.loadingCount === 0) {
- // 清除延迟显示的定时器
- if (this.loadingTimer) {
- clearTimeout(this.loadingTimer);
- this.loadingTimer = null;
- }
- // 移除 loading 元素
- if (this.loadingElement) {
- document.body.removeChild(this.loadingElement);
- this.loadingElement = null;
- }
- }
- },
- // 强制隐藏所有 loading
- forceHide() {
- this.loadingCount = 0;
- if (this.loadingTimer) {
- clearTimeout(this.loadingTimer);
- this.loadingTimer = null;
- }
- if (this.loadingElement) {
- document.body.removeChild(this.loadingElement);
- this.loadingElement = null;
- }
- },
- };
- // 注意:getUrlParams, getDeviceInfo, getJSessionId, saveJSessionId
- // 这些函数已在 common.js 中定义,这里直接使用全局函数
- const request = {
- async get(url, params = {}, options = {}) {
- return this.request(url, "GET", params, options);
- },
- async post(url, data = {}, options = {}) {
- return this.request(url, "POST", data, options);
- },
- async put(url, data = {}, options = {}) {
- return this.request(url, "PUT", data, options);
- },
- async delete(url, data = {}, options = {}) {
- return this.request(url, "DELETE", data, options);
- },
- async request(url, method, data, options = {}) {
- // 解析 loading 配置
- let loadingConfig;
- if (options.loading === false) {
- loadingConfig = false;
- } else {
- // 功能说明:H5 请求超时统一调到 11 分钟,避免审核/变动类慢接口过早超时 by xu 2026-03-09
- loadingConfig = {
- show: true,
- title: "加载中...",
- mask: true,
- delay: 300,
- timeout: 660000,
- ...(typeof options.loading === "object" ? options.loading : {}),
- };
- }
- // 解析请求配置
- // 功能说明:H5 axios 请求超时统一调到 11 分钟,和 loading 超时提示保持一致 by xu 2026-03-09
- const requestConfig = {
- timeout: 660000,
- ...options.request,
- };
- const shouldShowLoading =
- loadingConfig !== false && loadingConfig.show !== false;
- // 显示 loading
- if (shouldShowLoading) {
- loadingManager.show(loadingConfig);
- }
- // 获取设备信息
- const deviceInfo = getDeviceInfo();
- const devId = deviceInfo.deviceId || "";
- const sbmc = deviceInfo.model || "";
- // 处理URL,添加设备参数
- const separator = url.includes("?") ? "&" : "?";
- const finalUrl = `${url}${separator}devId=${devId}&sbmc=${sbmc}`;
- // 超时处理
- let timeoutTimer = null;
- if (shouldShowLoading && loadingConfig.timeout) {
- timeoutTimer = setTimeout(() => {
- loadingManager.hide();
- if (typeof showToastEffect !== "undefined") {
- showToastEffect("请求超时", 3000, "error");
- } else {
- // alert('请求超时')
- }
- }, loadingConfig.timeout);
- }
- try {
- // 配置axios请求
- const axiosConfig = {
- url: `${env.baseUrl}${finalUrl}`,
- method: method.toLowerCase(),
- timeout: requestConfig.timeout,
- headers: {},
- withCredentials: true,
- };
- // 处理请求数据
- if (method.toUpperCase() === "GET") {
- axiosConfig.params = data;
- } else {
- if (options.formData) {
- axiosConfig.headers["Content-Type"] =
- "application/x-www-form-urlencoded";
- // 转换为表单格式
- const formData = new URLSearchParams();
- Object.keys(data).forEach((key) => {
- const value = data[key];
- // 如果是数组,为每个元素单独添加参数(同名参数重复)
- if (Array.isArray(value)) {
- value.forEach((item) => {
- formData.append(key, item);
- });
- } else {
- formData.append(key, value);
- }
- });
- axiosConfig.data = formData;
- } else {
- axiosConfig.headers["Content-Type"] = "application/json";
- axiosConfig.data = data;
- }
- }
- // 发送请求
- const response = await axios(axiosConfig);
- const responseSessionId = getSessionIdFromResponseData(response.data);
- if (responseSessionId && typeof saveJSessionId === "function") {
- saveJSessionId(responseSessionId);
- }
- // 清除超时定时器
- if (timeoutTimer) {
- clearTimeout(timeoutTimer);
- }
- // 检查服务器处理错误
- if (
- response.data &&
- response.data.msg &&
- response.data.msg.includes("页面执行时错误")
- ) {
- throw new Error("服务器处理错误");
- }
- // 检查没有服务授权 - 直接回到小程序
- if (
- response.data &&
- response.data.msg &&
- response.data.msg.includes("没有服务授权")
- ) {
- handleH5NoServiceAuth(response.data.msg);
- throw new Error(response.data.msg);
- }
- // 会话失效时先静默恢复,同一用户只执行一次刷新。
- if (isLoginExpiredResponseData(response?.data)) {
- const authRetryCount = Number(options.__authRetryCount || 0);
- const shouldRecover =
- !options.skipAuthRecovery && authRetryCount < 1;
- if (shouldRecover) {
- try {
- await window.ensureMiniProgramSessionFresh({
- force: true,
- forceRecovery: true,
- bypassCooldown: true,
- page: window.location.pathname,
- service: url,
- });
- return await this.request(url, method, data, {
- ...options,
- loading: false,
- suppressErrorToast: true,
- skipAuthRecovery: false,
- __authRetryCount: authRetryCount + 1,
- });
- } catch (recoveryError) {
- const authStatus = recoveryError?.authStatus || "";
- if (
- authStatus === window.AUTH_RECOVERY_STATUS?.TOKEN_INVALID ||
- authStatus === window.AUTH_RECOVERY_STATUS?.NO_AUTH ||
- authStatus === window.AUTH_RECOVERY_STATUS?.USER_MISMATCH
- ) {
- redirectToManualLogin();
- }
- throw recoveryError;
- }
- }
- const authError = new Error(
- response?.data?.msg || response?.data?.message || "登录过期"
- );
- authError.isLoginExpired = true;
- throw authError;
- }
- // 返回与小程序兼容的格式
- return {
- data: response.data,
- };
- } catch (error) {
- // 清除超时定时器
- if (timeoutTimer) {
- clearTimeout(timeoutTimer);
- }
- // 部分服务直接返回 HTTP 401;与响应体失效码走同一套单飞恢复。
- if (!options.skipAuthRecovery && isLoginExpiredHttpError(error)) {
- const authRetryCount = Number(options.__authRetryCount || 0);
- if (authRetryCount < 1) {
- try {
- await window.ensureMiniProgramSessionFresh({
- force: true,
- forceRecovery: true,
- bypassCooldown: true,
- page: window.location.pathname,
- service: url,
- });
- return await this.request(url, method, data, {
- ...options,
- loading: false,
- suppressErrorToast: true,
- skipAuthRecovery: false,
- __authRetryCount: authRetryCount + 1,
- });
- } catch (recoveryError) {
- const authStatus = recoveryError?.authStatus || "";
- if (
- authStatus === window.AUTH_RECOVERY_STATUS?.TOKEN_INVALID ||
- authStatus === window.AUTH_RECOVERY_STATUS?.NO_AUTH ||
- authStatus === window.AUTH_RECOVERY_STATUS?.USER_MISMATCH
- ) {
- redirectToManualLogin();
- }
- throw recoveryError;
- }
- }
- }
- // 处理错误
- let errorMessage = "请求失败";
- if (error.response) {
- errorMessage = `请求失败: ${error.response.status}`;
- } else if (error.request) {
- errorMessage = "网络连接失败";
- } else {
- errorMessage = error.message || "未知错误";
- }
- if (
- typeof showToastEffect !== "undefined" &&
- !options.suppressErrorToast &&
- !error?.isLoginExpired
- ) {
- if (
- error?.authStatus === window.AUTH_RECOVERY_STATUS?.TEMPORARY_FAILURE
- ) {
- errorMessage = "登录状态暂时无法恢复,请稍后重试";
- }
- showToastEffect(errorMessage, 3000, "error");
- } else {
- // alert(errorMessage)
- }
- throw error;
- } finally {
- // 隐藏 loading
- if (shouldShowLoading) {
- loadingManager.hide();
- }
- }
- },
- };
- // 兼容旧页面调用:统一走单飞会话恢复,避免重复自动登录和递归刷新。
- const handleH5LoginExpired = async (options = {}) => {
- try {
- return await window.ensureMiniProgramSessionFresh({
- ...options,
- force: true,
- forceRecovery: true,
- bypassCooldown: true,
- page: options.page || window.location.pathname,
- });
- } catch (error) {
- const authStatus = error?.authStatus || "";
- if (
- authStatus === window.AUTH_RECOVERY_STATUS?.TOKEN_INVALID ||
- authStatus === window.AUTH_RECOVERY_STATUS?.NO_AUTH ||
- authStatus === window.AUTH_RECOVERY_STATUS?.USER_MISMATCH
- ) {
- redirectToManualLogin();
- }
- throw error;
- }
- };
- // H5没有服务授权处理
- const handleH5NoServiceAuth = (errorMsg) => {
- // 显示错误提示
- if (typeof showToastEffect !== "undefined") {
- // showToastEffect('没有服务授权,即将返回', 2000, 'error');
- } else {
- }
- // 延迟一下让用户看到提示,然后返回小程序
- setTimeout(() => {
- // 通知小程序返回
- if (typeof callNative === "function") {
- callNative("noServiceAuth", "没有服务授权", {
- error: true,
- message: errorMsg,
- action: "goBack",
- });
- } else {
- // 降级处理:直接关闭页面
- if (window.history.length > 1) {
- window.history.back();
- } else {
- window.close();
- }
- }
- }, 1500);
- };
- // 导出到全局
- window.request = request;
- window.handleH5LoginExpired = handleH5LoginExpired;
- window.handleH5NoServiceAuth = handleH5NoServiceAuth;
- console.log("✅ H5 Request工具已加载");
|