【问题标题】:How to resolve "Cannot read property 'forEach' of undefined" error [closed]如何解决“无法读取未定义的属性'forEach'”错误[关闭]
【发布时间】:2020-12-18 14:42:52
【问题描述】:

我正在尝试从我的 json 中读取所有值,但收到此错误:

TypeError: Cannot read property 'forEach' of undefined

我做错了什么?

fetch(url, {
            method: 'POST',
            headers: {
                "user-key": 'mykey'
            },
            body:               
                'fields id, name, cover.url; where id = 1942;'
        })
            .then(response => response.json())          
            .then((data) => {
                data.array.forEach(element => {
                    console.log(element)
                });
            })
            .catch((error) => console.log(error))

【问题讨论】:

    标签: javascript arrays json ajax api


    【解决方案1】:

    如何解决“无法读取未定义的属性'forEach'”错误

    您找到调用forEach 的位置(应该很容易找到,因为错误消息包含文件名和行号,不幸的是您对我们隐瞒了),然后确保无论您调用什么@ 987654322@ on 位于实际上作为forEach 属性的对象上;大概是Array

    【讨论】:

      【解决方案2】:

      json 响应的组织方式可能与您想象的不同。如果发布成功,它很可能会返回您在发布请求中发送的对象。这意味着您不能直接在其上使用 forEach 函数,而是在其键或值上使用,如果这是您所追求的。

      【讨论】:

        【解决方案3】:

        错误说明了一切。您正在尝试对未定义的值使用 ForEach。 您没有按照后端的要求接收数据。 数据必须采用特定的数据结构,您才能在其上使用 .forEach。

        检查你收到的是不是数组。

        例如:-

        console.log(typeof data.array);
        

        【讨论】:

          猜你喜欢
          • 2023-03-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-08-01
          • 2020-09-01
          • 1970-01-01
          • 2019-04-30
          相关资源
          最近更新 更多