javascript fetch api 如果URL不正确,则不会返回正确的错误文本。它总是返回,无法在 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".
}
尝试此
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