Javascript Fetch偶尔会返回404

问题描述 投票:0回答:1

我们发现偶尔我们的.fetch命令返回404.即使该文件存在并且经常被命中,它有时会收到404。

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,因为文件肯定存在。

javascript fetch fetch-api
1个回答
3
投票

这里经典的做法是重试操作,因为网络通信可能不可靠,特别是在移动设备上。但是瞬态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
});

inputinitused by the spec的名字fetch,所以这就是我上面使用的。)

© www.soinside.com 2019 - 2024. All rights reserved.