I am trying to find user with the entered email and password from this users dummy array but I get undefined in the return value and hence I am not able to login. If I run this code in console it fetches correct output. Can somebody help why this find function (in the post req) not working in Node?
Dummy array -
const users = [
{ id: 1, name: 'Sherry', email:'[email protected]', password: 1234 },
{ id: 2, name: 'harry', email:'[email protected]', password: 1234 },
{ id: 3, name: 'cherry', email:'[email protected]', password: 1234 }
]
Get Request -
app.get('/login', (req, res) => {
res.send(`<form method='POST' action='/login'>
<input type="email" name="email" placeholder="Enter email" />
<input type="password" name="password" placeholder="Enter pass" />
<input type="submit" />
</form>`);
})
Post Request -
app.post('/login', (req,res) => {
const { email, password } = req.body;
console.log(email)
console.log(password)
console.log(users)
let user1 = users.find((user) => user.email === email && user.password === password);
console.log(user1);
if(user1) {
req.session.userId = user.id
return res.redirect('/home')
}
res.redirect('/')
})
Issue - User1 is undefined.
CodePudding user response:
I would say the password
value received in req.body
is a string
. Your ===
comparator checks also a variables type
, and string
and number
won't match.
Option 1
I recommend to change your users data password
prop to string
:
const users = [
{ id: 1, name: 'Sherry', email:'[email protected]', password: '1234' },
{ id: 2, name: 'harry', email:'[email protected]', password: '1234' },
{ id: 3, name: 'cherry', email:'[email protected]', password: '1234' }
]
Option 2
If you want to only have numeric passwords you can also change your find
function to compare numbers correctly:
let user1 = users.find((user) => user.email === email && user.password === parseInt(password));
Please let me know if it worked.
CodePudding user response:
// Parse URL-encoded bodies (as sent by HTML forms)
app.use(express.urlencoded());
// Parse JSON bodies (as sent by API clients)
app.use(express.json());
This two line will make sure you sever-side will receive the data from req.body. First of all you were sending the data as a form data so you need to include
// Parse URL-encoded bodies (as sent by HTML forms)
app.use(express.urlencoded());
which will allow you to read the data from req.body.
app.post('/login', (req,res) => {
const { email, password } = req.body;
console.log('req',req.body)
console.log("email",email)
console.log("password",password)
let index = users.findIndex((user) => user.email === email && user.password == password);
console.log("index",index)
let user1= users[index]
console.log("user1",user1);
if(user1) {
console.log("HERE=======================")
req.session.userId = user1.id
return res.redirect('/home')
}
res.redirect('/')
})
Now try the above code snap, hopefull it will help you.