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
的名称,所以这就是我上面使用的名称。)
相关文章