[英]Cannot read property 'forEach' of undefined error JavaScript
this is my javascript code but whenever I try to run it, it throws 'Error: TypeError: Cannot read property 'forEach' of undefined' Can anyone please tell me why this is happening and also give me a solution how to fix it?这是我的 javascript 代码,但是每当我尝试运行它时,它都会抛出“错误:TypeError:无法读取未定义的属性 'forEach'”谁能告诉我为什么会发生这种情况,并给我一个解决方案如何解决它?
app.post('/getElements', (req, res) => {
fs.readFile('items.json', function(error, data) {
if (error) {
res.status(500).end()
} else {
try {
const accountId = req.body.accountId //the value of it is 'data'
const items = JSON.parse(data)
items.accountId.forEach(function(item) {
const price = item.price
res.json({
price: price
})
})
} catch (err) {
console.log('Error: ', err)
}
}
})
})
I would recommend to check if the data that comes in has the format you need, then only run your forEach
if accountId
is type of array.我建议检查传入的数据是否具有您需要的格式,然后仅当
accountId
是数组类型时才运行您的forEach
。 If not, return something like price not available
如果没有,返回类似
price not available
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.