JavaScript 获取API 不会返回正确的错误文本。它总是在 catch 语句中返回无法获取错误。
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".
}
答案 0 :(得分:1)
尝试
var myRequest = new Request('https://www.w3schools.com/nodejs/incorrecturl');
fetch(myRequest).then(function(response) {
console.log(response.status);
});
OR
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