Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to find array elements in npm?

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:'sherry@gmail.com', password: 1234 },   
            { id: 2, name: 'harry', email:'harry@gmail.com', password: 1234 },
            { id: 3, name: 'cherry', email:'cherry@gmail.com', password: 1234 }
        ]

Get Request –

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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:'sherry@gmail.com', password: '1234' },   
  { id: 2, name: 'harry', email:'harry@gmail.com', password: '1234' },
  { id: 3, name: 'cherry', email:'cherry@gmail.com', 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading