【问题标题】:How to use foreach on fetch response in vue?如何在 vue 中使用 foreach 获取响应?
【发布时间】:2021-07-24 21:30:04
【问题描述】:

我正在通过 fetch 获取数据,我想使用 foreach 循环,但它不工作

 fetch(url, options).then((response) => {
 
            response.json().forEach((work_order) => {
})
})

给出这个错误

Uncaught (in promise) TypeError: Cannot read property 'forEach' of undefined

控制台结果

Response {type: "cors", url: "http://siloc.xyz/api/gangBoss/workOrders/view/17", redirected: false, status: 200, ok: true, …}
body: (...)
bodyUsed: false
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: "OK"
type: "cors"
url: "http://siloc.xyz/api/gangBoss/workOrders/view/17"
__proto__: Response

【问题讨论】:

  • response.json() 返回一个 Promise - 奇怪的是它返回 undefined 虽然
  • 您应该收到undefined。我希望错误是TypeError: res.json().forEach is not a function?
  • 我刚刚在siloc.xyz 网站上运行了您的代码,我收到了错误TypeError: res.json().forEach is not a function。请您确定问题中的代码是您使用的代码吗?
  • 好的。如果这是错误(与您之前所说的不同),请尝试将 forEach 放入 then? response.json().then(data => data.forEach(...))
  • 我收到了我用相同代码突出显示的错误

标签: javascript vue.js vuejs3


【解决方案1】:

虽然fetch 自己发送请求,但在完全接收到服务器响应后,返回的承诺不会解析。

响应对象表示数据流。因此 - res.json() 返回另一个 promise

试试这个:

fetch(url, options).then(response => response.json()).then(jsonResponse => {
  if (Array.isArray(jsonResponse)) {
    jsonResponse.forEach((work_order) => {
      //...
    });
  } else {
    throw Error('Server response was not an array');
  }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-10
    • 2019-03-22
    • 2020-12-17
    • 2022-11-12
    • 2019-03-27
    • 1970-01-01
    相关资源
    最近更新 更多