uniapp的请求封装,如何避免重复提交请求

发布于:2025-06-14 ⋅ 阅读:(15) ⋅ 点赞:(0)

1、如何封装uniapp,并且如何使用uniapp的封装查看👉uniapp请求封装_uni-app-x 请求封装-CSDN博客​​​​​​​
2、声明一个请求记录的缓存,代码如下

// 存储请求记录
let requestRecords = {};
// 重复请求拦截时间(毫秒)
const INTERCEPT_DURATION = 2000;
const request = (url, data = {}, method = "GET", ContentType = "application/json") => {
  const requestObj = {
    data,
    url,
    time: Date.now(),
  };
  if (method !== "GET") {
    if (Object.keys(requestRecords).length == 0) {
      requestRecords = requestObj;
    } else {
      const s_url = requestRecords.url; // 请求地址
      const s_data = requestRecords.data; // 请求数据
      const s_time = requestRecords.time; // 请求时间
      if (
        s_data === requestObj.data &&
        requestObj.time - s_time < INTERCEPT_DURATION &&
        s_url === requestObj.url
      ) {
        uni.showToast({
          title: "数据正在处理,请勿重复提交",
          icon: "none",
          duration: 2000,
        });
        return;
      }
      requestRecords = requestObj;
    }
  }

  return new Promise(function (resolve, reject) {
    let header = {};
    if (uni.getStorageSync("token")) {
      header = {
        "Content-Type": ContentType,
        Authorization: uni.getStorageSync("token"),
      };
    } else {
      header = {
        "Content-Type": ContentType,
      };
    }
    if (Object.keys(data).length && !data.showLoading) {
      uni.showLoading({
        title: "加载中",
        mask: true,
      });
    }
    console.log("请求参数", data, url);
    uni.request({
      url: BASE_URL + url,
      data,
      method,
      header,
      success: function (res) {
        console.log("res", res);
        if (res.data.code == 200) {
          resolve(res.data);
        } else if (res.data.code == 401) {
          uni.navigateTo({
            url: "/pages/login/login",
          });
        } else {
          if (Object.keys(res.data).length && !data.showLoading) {
            uni.showToast({
              title: res.data.msg,
              icon: "none",
              duration: 2000,
            });
          }
          reject(res);
        }
      },
      fail: function (err) {
        console.log("err", err);
        uni.getNetworkType({
          success: function (res) {
            console.log("当前网络状态:", res.networkType);
            if (res.networkType === "none") {
              console.log("当前无网络");
              uni.showToast({
                title: "当前网络不可用,请检查网络连接",
                icon: "none",
              });
              return;
            } else {
              uni.showToast({
                title: "加载失败,请稍后重试!",
                icon: "none",
                duration: 2000,
              });
            }
          },
        });
        reject(err);
      },
      complete: function () {
        console.log("结束");
        if (!data.showLoading) {
          uni.hideLoading();
        }
      },
    });
  });
};