如果 URL 不正确,JavaScript fetch API 不会返回正确的错误文本。它总是在 catch 语句中返回 fail to fetch 错误。
window.onload = () => {
fetch("https://www.w3schools.com/nodejs/incorrecturl")
.then(res => res.json())
.then(data => console.log(data))
.catch(error => alert(error.toString())) // Here i need proper error message, instead of "failed to fetch".
}
最佳答案
试试这个
var myRequest = new Request('https://www.w3schools.com/nodejs/incorrecturl');
fetch(myRequest).then(function(response) {
console.log(response.status);
});
或
fetch('https://www.w3schools.com/nodejs/incorrecturl').then(function(response) {
console.log(response.status);
});
引用:https://developer.mozilla.org/en-US/docs/Web/API/Response/status
关于javascript - 如果 URL 不正确,fetch API 不会在 catch 中显示确切的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56268679/