设置5秒超时请求处理

This commit is contained in:
anln 2024-11-13 17:46:45 +08:00
parent 12b19ce52e
commit b9d475db37
1 changed files with 56 additions and 3 deletions

View File

@ -1,14 +1,23 @@
import baseRequest from "./baseRequest";
import { get } from "./storeInfo";
import { Toast } from "antd-mobile";
// import { useRouter } from "next/navigation";
// import webviewBaseRequest from "@/utils/webviewBaseRequest";
// 创建一个封装 fetch 的函数
export default function customFetch(method, url, options = {}, needMid) {
const controller = new AbortController();
const signal = controller.signal;
// 设置超时
const timeout = setTimeout(() => {
controller.abort("Request timed out");
}, 5000);
const base = baseRequest();
// 默认选项
const defaultOptions = {
method: method,
signal,
headers: {
"Content-Type": "application/json",
"X-Req-Source-TF": "wittgenstein",
@ -32,18 +41,62 @@ export default function customFetch(method, url, options = {}, needMid) {
return new Promise((resolve, reject) => {
fetch(url, mergedOptions)
.then((response) => {
clearTimeout(timeout);
// // 检查响应状态码
// if (!response.ok) {
// throw new Error(`HTTP error! status: ${response.status}`);
if (!response.ok) {
throw new Error("Network response was not ok " + response.statusText);
}
// const contentLength = response.headers.get("Content-Length");
// if (!contentLength) {
// throw new Error("Content-Length is null");
// }
// const total = parseInt(contentLength, 10);
// let loaded = 0;
const reader = response.body.getReader();
const stream = new ReadableStream({
start(controller) {
function push() {
reader.read().then(({ done, value }) => {
if (done) {
controller.close();
return;
}
// loaded += value.byteLength;
// const progress = (loaded / total) * 100;
// console.log(`Progress: ${progress.toFixed(2)}%`);
controller.enqueue(value);
push();
}).catch((error) => {
controller.error(error);
})
};
push();
},
});
const newResponse = new Response(stream);
return newResponse.json();
// 解析 JSON 响应
return response.json();
// return response.json();
})
.then((data) => {
// 解析成功,返回数据
resolve(data);
})
.catch((error) => {
if (error.name === "AbortError") {
// console.log("Fetch request timed out.");
Toast.show({
icon: "fail",
content: "请求超时,请检查网络后重试。",
position: "top",
});
// 这里可以实现重试逻辑
// fetchDataWithRetry();
} else {
console.error("Fetch error:", error);
}
// console.log("error", error);
// Toast.show({
// icon: "fail",