Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

199
Views
Condition if/else don't work like expected in nodejs

I'm creating a simple api witch verify if the username and/or password are in the DB and if they are correct.

When I post correct data, it works. When I post a wrong password, it also works. But when I post a wrong username, my condition don't jump to the else. If the username is wrong, it means it is not in the DB. But here, it is like if it was in the DB, but he is not, so I get an error : " TypeError: Cannot read properties of undefined (reading 'Username') "

Here the code

app.post('/login', function(req, res) {
    (async () => {
    const bcrypt = require('bcrypt')

    
    try {
        username = req.query.username
        password = req.query.password

        let salt = await bcrypt.genSalt(10)
        let hash = await bcrypt.hash(password, salt)

        db_conn.getConnection( (err, conn) => {
            
            if(err) throw err;
            
            conn.query("SELECT * FROM mod803_appusers WHERE Username=? ", [username], (err, rows) => {

                //Problem here : when I put a wrong password, it's ok, this condition works because there is a password, and if bcrypt.compare is true, it sends response, but if it's false, it sends 'Wrong password'.
                //But if the Username is Wrong, it means there is no username in the DB. So here, I want this condition jump to the else : 'Incorrect username' but it doesn't.

                if(rows[0]['Username'] && rows[0]['Password']) {
                    bcrypt.compare(password, rows[0]['Password'], function(err, result) {
    
                        if(result){
                            
                            res.send({"table": rows});
    
                        } else {
                            res.send("Wrong password");
    
                    }}); 
                    

                } else {
                    res.send('Incorrect username');

                }
                
            })
            
        })

    } catch (error) {
        console.log(error.message)
    }
})()

})

Thanks

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!