Javascript Fetch returns 404 occasionally(JavaScript FETCH偶尔返回404)
问题描述
我们发现,我们的.fetch命令偶尔会返回404。即使该文件存在并且经常被点击,有时它也会收到404。 数据-lang="js"数据-隐藏="假"数据-控制台="真"数据-巴贝尔="假">
window.fetch('/category/somepage', {
credentials: 'same-origin',
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(app.addAntiForgeryToken(postData))
})
.then(function(response) {
if (response.ok) {
return response.json();
}
throw new Error('Network response was not ok');
})
.then(result => {
if (result.Status === 'OK') {
//...
}
})
目前正在使用throw new Error捕获它。
由于我们需要解决此问题,强制再次尝试此操作直到页面命中的最佳方式是什么?我们是否应该显示一个重试按钮,或者有什么方法可以循环执行该按钮?我不确定这为什么会抛出404,因为该文件肯定一直存在。
推荐答案
此处的典型做法是重试该操作,因为网络通信可能不可靠,尤其是在移动设备上。但瞬时404是另一个问题,它指向Web服务器的问题,可能需要单独诊断。(例如:如果是充当单个终结点的Web服务器群集,则其中一个服务器可能配置错误,因此找不到其他服务器可以找到的资源。)
但对于暂时性故障,典型的做法是重试:
function fetchJSONWithRetry(input, init, retries = 10) {
return fetch(input, init)
.then(function(response) {
if (response.ok) {
return response.json();
}
throw new Error('Network response was not ok'); // I usually use `new Error("HTTP status " + response.status)`
})
.catch(error => {
if (retries <= 0) {
throw error;
}
return fetchJSONWithRetry(input, init, retries - 1);
});
}
用法如下:
fetchJSONWithRetry('/category/somepage', {
credentials: 'same-origin',
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(app.addAntiForgeryToken(postData))
})
.then(result => {
if (result.Status === 'OK') {
// ...
}
})
.catch(error => {
// All retries failed, handle it
});
(input和init是throw new Error的名称,所以这就是我上面使用的名称。)
这篇关于JavaScript FETCH偶尔返回404的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:JavaScript FETCH偶尔返回404
基础教程推荐
- 如何添加到目前为止的天数? 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
