真的没有办法从失败的 js 获取请求中获取响应主体吗?
Is there really no way to get the response body from a failed js fetch request?
如果请求失败 (400),新的 js 获取 API 会失败:
fetch(uri).catch(function(err) {
console.log(err);
});
出现这种情况真的没有办法获取到response body吗?例如检查错误代码。
编辑:我创建了一个 js fiddle:https://jsfiddle.net/4x4xLwqo/ that calls this mockbin endpoint: http://mockbin.org/bin/d87acbb0-526e-4d66-aea4-b827d9c35031/view
编辑 2:更新 jsfiddle 以使用更好的端点:https://jsfiddle.net/4x4xLwqo/2/
如果遇到 HTTP 错误,fetch
不会进入 catch
。您可以使用常规 then
.
来处理
来自MDN:
A fetch()
promise will reject with a TypeError
when a network error is encountered, although this usually means permission issues or similar — a 404 does not constitute a network error, for example. An accurate check for a successful fetch()
would include checking that the promise resolved, then checking that the Response.ok
property has a value of true.
以及来自 MDN 的附带示例:
fetch('flowers.jpg').then(function(response) {
if(response.ok) {
response.blob().then(function(myBlob) {
var objectURL = URL.createObjectURL(myBlob);
myImage.src = objectURL;
});
} else {
console.log('Network response was not ok.');
}
})
.catch(function(error) {
console.log('There has been a problem with your fetch operation: ' + error.message);
});
如果请求失败 (400),新的 js 获取 API 会失败:
fetch(uri).catch(function(err) {
console.log(err);
});
出现这种情况真的没有办法获取到response body吗?例如检查错误代码。
编辑:我创建了一个 js fiddle:https://jsfiddle.net/4x4xLwqo/ that calls this mockbin endpoint: http://mockbin.org/bin/d87acbb0-526e-4d66-aea4-b827d9c35031/view
编辑 2:更新 jsfiddle 以使用更好的端点:https://jsfiddle.net/4x4xLwqo/2/
fetch
不会进入 catch
。您可以使用常规 then
.
来自MDN:
A
fetch()
promise will reject with aTypeError
when a network error is encountered, although this usually means permission issues or similar — a 404 does not constitute a network error, for example. An accurate check for a successfulfetch()
would include checking that the promise resolved, then checking that theResponse.ok
property has a value of true.
以及来自 MDN 的附带示例:
fetch('flowers.jpg').then(function(response) {
if(response.ok) {
response.blob().then(function(myBlob) {
var objectURL = URL.createObjectURL(myBlob);
myImage.src = objectURL;
});
} else {
console.log('Network response was not ok.');
}
})
.catch(function(error) {
console.log('There has been a problem with your fetch operation: ' + error.message);
});