如何解决"Cannot read property 'forEach' of undefined"错误



我正试图从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))

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

您找到调用forEach的位置(应该很容易找到,因为错误消息包含文件名和行号,不幸的是,您一直瞒着我们(,然后确保对其调用forEach的内容都在对象上,该对象实际上是forEach属性;推测为CCD_ 4。

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

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

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

例如:-

console.log(typeof data.array);

最新更新