无法读取未定义错误 JavaScript 的属性'forEach'



这是我的javascript代码,但每当我尝试运行它时,它都会抛出'Error:TypeError:Cannot read property'forEach'of undefined'有人能告诉我为什么会发生这种情况,并给我一个如何修复的解决方案吗?

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)
}
}
})
})

我建议检查传入的数据是否具有所需的格式,然后仅在accountId是数组类型的情况下运行forEach。如果没有,返回类似price not available的内容

最新更新