I'm building a small server for an auction app with 3 hard coded users.
To match the username and password with the hard coded users details when they sign in, I'm using a for loop inside my POST request. It only works for the first user, so it seems my loop might not iterate through the other two users.
Here is my hard coded database:
const database = {
users: [
{
username: 'User1',
password: 'IamUserOne',
itemOneBid: 0,
itemTwoBid: 0,
itemThreeBid: 0,
itemFourBid: 0,
itemFiveBid: 0,
itemSixBid: 0,
},
{
username: 'User2',
password: 'IamUserTwo',
itemOneBid: 0,
itemTwoBid: 0,
itemThreeBid: 0,
itemFourBid: 0,
itemFiveBid: 0,
itemSixBid: 0,
},
{
username: 'Admin',
password: 'IamTheBoss'
}
]
}
This is my Post request:
app.post('/signin', (req, res) => {
for (var i=0; i < database.users.length; i++) {
if (req.body.username === database.users[i].username &&
req.body.password === database.users[i].password) {
res.json('successful signin');
} else {
res.status(400).json('error logging in');
}
}
})
It works fine if I sign in using the first user's details, but I get a 400 if I try the other users.
I can make it work without using a for loop as such:
app.post('/signin', (req, res) => {
if(req.body.username === database.users[0].username &&
req.body.password === database.users[0].password) {
res.json('successful signin');
} else if (req.body.username === database.users[1].username &&
req.body.password === database.users[1].password) {
res.json('successful signin');
} else if (req.body.username === database.users[2].username &&
req.body.password === database.users[2].password) {
res.json('successful signin');
} else {
res.status(400).json('error logging in');
}
})
I'm attempting to use a for loop just for cleaner code, knowing that I would use an actual database anyway in a real scenario. But I like a challenge! I'm just struggling with this one.
Any help would be immensely appreciated, thanks in advance!
question from:
https://stackoverflow.com/questions/65859119/node-js-problem-looping-through-post-request-featuring-an-if-else-statement