Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

198
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda