Search code examples
node.jsexpresssession-cookies

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 -

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.