Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

200
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda