为什么获取将返回“ TypeError:无法获取”,而不仅仅是“无法获取”?

时间:2019-12-13 07:17:12

标签: javascript ecmascript-6 fetch

我正在运行此代码并在没有互联网连接的情况下进行测试:

fetch(url, options)
  .then(res => {
    // irrelevant, as catch happens immediately on no network connection
  })
  .catch(err => {
    console.log('Failed fetch ', err);
  });

“ TypeError”是什么意思?

2 个答案:

答案 0 :(得分:1)

您的代码段应该记录

Failed fetch TypeError: ...
如果获取不成功,则会抛出

TypeError

更多信息,请检查

  1. https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Checking_that_the_fetch_was_successful
  2. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError

答案 1 :(得分:0)

遇到网络错误时,fetch()承诺将拒绝并显示TypeError。

plus,首先获得一个可解决的promise对象。您应该在之后使用,例如:

fetch(url, options)
  .then(res =>res.json())
  .then(data=>{console.log('data from server',JSON.stringify(data))})
  .catch(err => {
    console.log('Failed fetch ', err);
  });

Checking that the fetch was successful