Javascript 获取API不需要';如果URL不正确,则不会在catch中显示确切的错误

Javascript 获取API不需要';如果URL不正确,则不会在catch中显示确切的错误,javascript,promise,try-catch,fetch,Javascript,Promise,Try Catch,Fetch,如果URL不正确,JavaScript获取API不会返回正确的错误文本。它总是在catch语句中返回fail to fetch错误 window.onload=()=>{ 取回(“https://www.w3schools.com/nodejs/incorrecturl") .then(res=>res.json()) .then(数据=>console.log(数据)) .catch(error=>alert(error.toString())//这里我需要正确的错误消息,而不是“无法获取”

如果URL不正确,JavaScript获取API不会返回正确的错误文本。它总是在catch语句中返回fail to fetch错误

window.onload=()=>{
取回(“https://www.w3schools.com/nodejs/incorrecturl")
.then(res=>res.json())
.then(数据=>console.log(数据))
.catch(error=>alert(error.toString())//这里我需要正确的错误消息,而不是“无法获取”。
}
试试这个

var myRequest = new Request('https://www.w3schools.com/nodejs/incorrecturl');
fetch(myRequest).then(function(response) {
    console.log(response.status);
});


参考文献:

为什么不只是提醒一条自定义消息,而不是它返回的错误?但我如何才能找到不正确的url。如果返回404或500,则表示我可以识别。@shanmu92您没有收到服务器错误,因为服务器未配置为使用web服务。如果您想看到错误,那么您需要在google chrome浏览器上下载扩展名Allow Control Allow Origin在此扩展名中添加您的URL。然后运行脚本,然后得到正确的服务器错误。谢谢通过运行您的代码片段,我得到了这个错误
json输入的意外结束
您到底得到了什么脚本错误?这也是我在应用程序中处理事情的方式@Shanmu92
未捕获(承诺中)类型错误:无法获取
@BhanwarChaudhary
fetch('https://www.w3schools.com/nodejs/incorrecturl').then(function(response) {
    console.log(response.status);
});