简体   繁体   English

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

[英]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.

相关问题 无法读取未定义的属性“forEach” - Firebase 和 Javascript - Cannot read property "forEach" of undefined - Firebase and Javascript 类型错误:无法读取未定义 Javascript 的属性“forEach” - TypeError: Cannot read property 'forEach' of undefined Javascript 类型错误:无法读取未定义的属性“forEach”,javascript - TypeError: Cannot read property 'forEach' of undefined , javascript 错误:TypeError:无法读取未定义的属性“forEach” - Error : TypeError: Cannot read property 'forEach' of undefined 错误:无法读取未定义的属性“ forEach” - Error : Cannot read property 'forEach' of undefined 无法读取未定义的属性“forEach” - Cannot read property 'forEach' of undefined 在javascript变量中使用php输出会导致无法读取未定义错误的属性“ forEach” - using php output in the javascript variable gives Cannot read property 'forEach' of undefined error Javascript 提取后无法读取未定义的属性“forEach” - Javascript Cannot read property 'forEach' of undefined after fetch javascript UnhandledPromiseRejectionWarning:TypeError:无法读取未定义的属性'forEach' - javascript UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'forEach' of undefined 量角器,JavaScript比较:无法读取未定义的属性“ forEach” - protractor, JavaScript Comparison: Cannot read property 'forEach' of undefined
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM