【问题标题】:object/json destructuring inside fetch (then)fetch 内部的对象/json 解构(然后)
【发布时间】:2020-07-09 07:28:44
【问题描述】:

不知道这是否是个好问题,因为我是 JavaScript 的初学者,但我想在 fetch api 中使用解构得到错误:

Uncaught (in promise) TypeError: response is not iterable

问题出在哪里,解决问题的好方法是什么?如果可能的话,你可以用 response.json 写两个版本,一个不写。提前致谢。

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width">
  <style>

  </style>
</head>

<body>
  <script>
    fetch("https://o", {
      method: "GET",
      headers: {
        "Content-type": "application/json",
        "X-API-Key": "***"
      }
    })
      .then((response) => {
        //   response.json().then(function(json) {
        const [b] = response

        //console.log(json)
        console.log(b)
      });
//   })
  </script>

</body>

</html>

【问题讨论】:

    标签: javascript html arrays fetch fetch-api


    【解决方案1】:

    很可能response 不是一个数组。

    如果response 有一个名为b 的属性,那么我会尝试如下解构:

    const { b } = response;
    

    考虑如下:

    const response = { b: { text: 'text', num: 123 } };
    const { b } = response;
    console.log(b);

    我希望这会有所帮助!

    【讨论】:

    • 当我使用这个 'const { b } = response; 时,我现在得到了 'undefined' '
    • @walee 这意味着response 没有名为b 的属性。你可以试试console.log(response) 看看你那里有什么属性吗?
    • @norbitrial 其在数组中的对象
    • @walee 你能把它粘贴到这里吗?谢谢!
    • const { 数据 } = 响应
    【解决方案2】:

    如果你愿意,你也可以这样使用 fetches ;

    fetch(url).then(response => response.json()
    .then(data => //you can use whatever action you want to do there
    

    然后第一个返回响应元素给你,你把这个响应元素转换成json格式。在第二个中,您访问 json 格式元素并随心所欲地使用它。

    如果你想了解更多关于这个主题的信息,可以搜索 Promise 对象。

    如果你愿意,你也可以对 api 请求使用 async-await 结构。它更短,更容易理解。

    async function getData(){
    const response = await fetch(**your url**);
    const data = await response.json();
    return data; 
    }
    

    这样,使用方法与 fetch 方法相同。祝你好运 !

    【讨论】:

      猜你喜欢
      • 2018-07-18
      • 2017-08-13
      • 1970-01-01
      • 1970-01-01
      • 2021-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-20
      相关资源
      最近更新 更多