【发布时间】:2021-01-31 15:49:42
【问题描述】:
刚接触 Fetch API 的初学者。我正在尝试console.log 当有人试图获取一个不存在但它不起作用的文件时出现的错误消息。它只是。谁能解释一下我哪里出错了。
document.getElementById('button1').addEventListener('click', getText);
//getText function
function getText() {
//fetching file that doesn't exist to produce the error
fetch('text.text')
.then(function(response){
return response.text();
})
.then(function(data){
console.log(data);
})//what's supposed to happen when the error is caught
.catch(function(error){
console.log(error);
})
}
【问题讨论】:
-
当您在发回 404 页面的服务器上运行此程序时,从技术上讲,获取请求并没有失败。但是,您可以查看
response.status === 404 -
@ChrisG - 是的。我见过的最近最糟糕的 API 决策之一。 :-)
标签: javascript try-catch