Reputation: 374
I get the TypeError: Cannot read property 'forEach' of undefined. I don't know what is wrong with the below code:
app.post("/entershop", (request, response)=> {
let username = request.body.uname;
let psw = request.body.psw;
let rawdata = fs.readFileSync('mapping.json');
let rootdata = JSON.parse(rawdata);
let isvalid = false;
let shops = rootdata["shops"];
shops.forEach(function(shop) {
var password = shop[username][0];
if(password === psw)
{
console.log('successful login');
}
else
{
console.log('login unsuccessful');
}
});
});
The error is displayed as below in the web page:
TypeError: Cannot read property 'forEach' of undefined
at app.post (/home/ubuntu/TheRandomShops/index_test.js:33:15)
at Layer.handle [as handle_request] (/home/ubuntu/TheRandomShops/node_modules/express/lib/router/layer.js:95:5)
at next (/home/ubuntu/TheRandomShops/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/home/ubuntu/TheRandomShops/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/home/ubuntu/TheRandomShops/node_modules/express/lib/router/layer.js:95:5)
at /home/ubuntu/TheRandomShops/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/home/ubuntu/TheRandomShops/node_modules/express/lib/router/index.js:335:12)
at next (/home/ubuntu/TheRandomShops/node_modules/express/lib/router/index.js:275:10)
at serveStatic (/home/ubuntu/TheRandomShops/node_modules/serve-static/index.js:75:16)
at Layer.handle [as handle_request] (/home/ubuntu/TheRandomShops/node_modules/express/lib/router/layer.js:95:5
And the mapping.json
looks like below:
{
"owners":[
{"name":"Bala", "id":"1", "psw":"bala"},
{"name":"Rohit", "id":"2", "psw":"Rohit"}
],
"employees":[
{"name":"Krithi", "owners":"Bala", "psw":"Krithi"},
{"name":"Kumar", "owners":"Rohit", "psw":"Kumar"}
]
}
Your help would be highly appreciated.
Upvotes: 0
Views: 1633
Reputation: 1113
Hope this will resolve your issue
app.post("/entershop", (request, response)=> {
let username = request.body.uname;
let psw = request.body.psw;
let rawdata = fs.readFileSync('mapping.json');
let rootdata = JSON.parse(rawdata);
let isvalid = false;
let shops = rootdata["shops"]||[];
shops.forEach(function(shop) {
var password = shop[username][0];
if(password === psw)
{
console.log('successful login');
}
else
{
console.log('login unsuccessful');
}
});
});
Upvotes: 2
Reputation: 91
rootdata is empty because there is nothing called shop in your data
Upvotes: 0