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();}},});});
};
?