JavaScript FETCH偶尔返回404 [英] Javascript Fetch returns 404 occasionally

查看:19
本文介绍了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
});

(inputinitthrow new Error的名称,所以这就是我上面使用的名称。)

这篇关于JavaScript FETCH偶尔返回404的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆