tiefen_space_h5/utils/requireAPI.js

59 lines
1.6 KiB
JavaScript
Raw Normal View History

2024-07-03 19:59:39 +08:00
import baseRequest from "./baseRequest";
2024-07-12 22:52:48 +08:00
import { get } from "./storeInfo";
2024-07-22 14:38:59 +08:00
2024-07-12 22:52:48 +08:00
// import { useRouter } from "next/navigation";
2024-07-03 19:59:39 +08:00
// import webviewBaseRequest from "@/utils/webviewBaseRequest";
2024-07-17 16:58:27 +08:00
2024-07-03 19:59:39 +08:00
// 创建一个封装 fetch 的函数
2024-07-12 22:52:48 +08:00
export default function customFetch(method, url, options = {}, mid) {
2024-07-17 16:58:27 +08:00
const base = baseRequest();
2024-07-12 22:52:48 +08:00
// 默认选项
const defaultOptions = {
method: method,
headers: {
"Content-Type": "application/json",
"X-Req-Source-TF": "wittgenstein",
...options?.headers,
// 可以添加其他默认头部信息
},
// 可以添加其他默认选项
};
let newBody = { ...options?.body };
if (mid) {
2024-07-22 14:38:59 +08:00
let mid = get("account").mid;
newBody.mid = mid;
2024-07-12 22:52:48 +08:00
}
const body = JSON.stringify({ ...base, ...newBody });
2024-07-31 20:05:17 +08:00
// console.log("newBody", body,url);
2024-07-08 20:07:36 +08:00
2024-07-12 22:52:48 +08:00
// 合并选项
const mergedOptions = { ...defaultOptions, body };
// console.log("mergedOptions",mergedOptions)
// 返回 Promise 对象
return new Promise((resolve, reject) => {
fetch(url, mergedOptions)
.then((response) => {
// 检查响应状态码
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
// 解析 JSON 响应
return response.json();
})
.then((data) => {
// 解析成功,返回数据
resolve(data);
})
.catch((error) => {
2024-07-22 16:41:33 +08:00
// console.log("error", error);
2024-07-22 14:38:59 +08:00
// Toast.show({
// icon: "fail",
// content: error.toString(),
// position: "top",
// });
2024-07-12 22:52:48 +08:00
// 请求失败,拒绝 Promise
reject(error);
});
});
}