Files
ruo-shan-cloud-pharmacy/miniprogram/utils/request.ts
T
2026-08-12 11:47:51 +08:00

102 lines
3.4 KiB
TypeScript

import { BASE_URL } from "../env";
import { base64Encode } from "./crypto";
type RequestProps = {
options: WechatMiniprogram.RequestOption;
loadingTitle?: string;
isLoading?: boolean;
needLogin?: boolean;
};
// 每次请求动态生成 header,确保使用最新的 openId
const fingerprint = wx.getSystemInfoSync();
export const request = <T = any>(
{ options, loadingTitle = "加载中", isLoading = true, needLogin = true }: RequestProps
): Promise<T> => {
const app = getApp<IAppOption>();
const header: any = {
"X-Fingerprint": fingerprint,
};
if (needLogin) {
if (!app.checkLoginState()) {
return Promise.reject(new Error('请先登录'));
}
const openId = wx.getStorageSync("openId") || "";
const appId = wx.getStorageSync("appId") || "";
header.Authorization = `Basic ${base64Encode(`${openId}:${appId}`)}`
}
return new Promise((resolve, reject) => {
let showToast = false;
if (isLoading) {
wx.showLoading({
title: loadingTitle,
mask: true // 防止触摸穿透
});
}
wx.request({
header,
method: options.method || "POST",
...options,
url: `${BASE_URL}/api${options.url}`,
success(res: any) {
if (res.statusCode == 200) {
if (!res.data.code || res.data.code === 200) {
resolve(res.data as T);
} else if (res.data.code === 401) {
wx.showModal({
title: "登录提示",
content: "请先登录",
confirmText: "去登录",
success: (options) => {
if (options.confirm) {
wx.navigateTo({ url: "/pages/login/login" });
}
}
});
reject(res);
} else {
if (isLoading) {
showToast = true;
wx.showToast({
icon: "none",
title: `${res.data.msg ? res.data.msg : res.errMsg}`,
duration: 2000,
});
}
reject(res);
}
} else {
if (isLoading) {
showToast = true;
wx.showToast({
icon: "none",
title: `请求错误:${res.data.msg ? res.data.msg : res.errMsg}`,
duration: 2000,
});
}
reject(res);
}
},
fail(err) {
if (isLoading) {
showToast = true;
wx.showToast({
icon: "none",
title: "网络异常,请检查网络",
duration: 2000,
});
}
reject(err);
},
complete() {
if (isLoading && !showToast) {
wx.hideLoading();
}
},
});
});
};