This commit is contained in:
cao123
2026-09-07 09:03:11 +08:00
parent de47ffc773
commit 78bc9e3c86
4 changed files with 43 additions and 31 deletions
+29 -18
View File
@@ -1,4 +1,5 @@
import { BASE_URL } from "../env";
import { BASE_URL, appId } from "../env";
import { base64Encode } from "./crypto";
type RequestProps = {
options: WechatMiniprogram.RequestOption;
loadingTitle?: string;
@@ -6,27 +7,23 @@ type RequestProps = {
needLogin?: boolean;
};
// 生成设备指纹字符串
const generateFingerprint = (): string => {
const info = wx.getSystemInfoSync();
return [
String(info.system),
String(info.platform),
String(info.SDKVersion),
String(info.screenWidth),
String(info.screenHeight),
].join("&");
};
// 每次请求动态生成 header,确保使用最新的 openId
const fingerprint = wx.getSystemInfoSync();
export const request = <T = any>(
{ options, loadingTitle = "加载中", isLoading = true }: RequestProps
{ options, loadingTitle = "加载中", isLoading = true, needLogin = true }: RequestProps
): Promise<T> => {
const app = getApp<IAppOption>();
const header: any = {
"X-Fingerprint": generateFingerprint(),
"X-Fingerprint": fingerprint,
};
if (needLogin) {
if (!app.checkLoginState()) {
return Promise.reject(new Error('请先登录'));
}
const openId = wx.getStorageSync("openId") || "";
header.Authorization = `Basic ${base64Encode(`${openId}:${appId}`)}`
}
return new Promise((resolve, reject) => {
let showToast = false;
@@ -47,13 +44,27 @@ export const request = <T = any>(
if (!res.data.code || res.data.code === 200) {
resolve(res.data as T);
} else if (res.data.code === 401) {
// 保存当前页面路径,登录后跳转回来
const pages = getCurrentPages();
const currentPage = pages[pages.length - 1];
if (currentPage) {
const route = `/${currentPage.route}`;
const options = currentPage.options || {};
const query = Object.entries(options)
.filter(([, value]) => value !== undefined && value !== null)
.map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value as string)}`)
.join("&");
const fullPath = query ? `${route}?${query}` : route;
wx.setStorageSync("redirectPath", fullPath);
}
wx.showModal({
title: "登录提示",
content: "请先登录",
confirmText: "去登录",
success: (options) => {
if (options.confirm) {
wx.navigateTo({ url: "/pages/login/login" });
// 使用 redirectTo 替换当前页,登录页无返回按钮
wx.redirectTo({ url: "/pages/login/login" });
}
}
});