我在 React js 中使用 fetch post 方法,当向后端发送请求时,需要 7 分钟才能提供响应,然后前端会自动超时。你能帮我解决一下如何在 fetch 方法中设置 10 分钟的时间,让前端等待响应,并且只有当后端花费超过 10 分钟时才会超时。
如果我必须安装任何依赖项,请告诉我们。
另外只是为了通知您我已经安装了依赖项“whatwg-fetch-timeout”:“^2.0.2-timeout”并且它在开发服务器上运行良好
但是当尝试创建构建包时,它无法创建构建。
示例代码:
fetch("http://" + hostName + ":" + port + "/searchData", {
method: "POST",
headers: {
"Content-Type": "application/json",
Login: login,
ID: id
},
body: JSON.stringify({
StartDate: StartDate === "" ? null : StartDate,
EndDate: EndDate === "" ? null : EndDate,
FileName: FileName === "" ? null : FileName,
RecordCount: RecordCount === "" ? null : RecordCount,
Status: Status
})
})
.then(response => {
resStatus = response.status;
return response.json();
})
.then(responseJson => {
//source code
})
.catch(error => {});
添加自己的超时怎么样
就像是
function timeoutPromise(ms, promise) {
return new Promise((resolve, reject) => {
const timeoutId = setTimeout(() => {
reject(new Error("promise timeout"))
}, ms);
promise.then(
(res) => {
clearTimeout(timeoutId);
resolve(res);
},
(err) => {
clearTimeout(timeoutId);
reject(err);
}
);
})
}
然后用 ES7 async/await 语法调用它
async request() {
try {
let res = await timeoutPromise(10*60*1000, fetch('/hello'));
} catch(error) {
// might be a timeout error
}
}
也供参考获取API请求超时? https://stackoverflow.com/questions/46946380/fetch-api-request-timeout尝试这个。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)