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

373
Vistas
Why is my response call out of scope and not working? NodeJs, Bcrypt, Express, MySQL

I am using Nodejs and MySQL to validate user passwords. I am having a hard time accessing my response (res) object to send a response back to the client. For some reason it works above my bcrypt function but not below. I need to access it below so I can send my JWT token back to the client. See below code examples. Thanks.

**WORKING EXAMPLE**
**res.send(data) is properly sending data back to the client**

app.post("/login", jsonParser,(req, res) => {
    let selectQuery = 'SELECT * FROM ?? WHERE ?? = ?';  
    let query = mysql.format(selectQuery,["users","username", req.body.username]);

    pool.query(query,(err, data) => {
        if(err) {
            console.error(err);
        }
//works here---> res.send(data)

        let match = bcrypt.compareSync(req.body.password, 
        data[0].password)
        console.log(match)
        
        match ? token = generateToken(data[0]): token = null
    })
})
**NON-WORKING EXAMPLE** 
**res.send(data) is NOT sending data back to the client. TIMED OUT**

   app.post("/login", jsonParser,(req, res) => {
    let selectQuery = 'SELECT * FROM ?? WHERE ?? = ?';  
    let query = mysql.format(selectQuery,["users","username", req.body.username]);

    pool.query(query,(err, data) => {
        if(err) {
            console.error(err);
        }
     
        let match = bcrypt.compareSync(req.body.password, data[0].password)
        console.log(match)

//not here----> res.send(data)
    
        match ? token = generateToken(data[0]): token = null
    })
})

**The same code using try catch**
app.post("/login", jsonParser,(req, res) => {
    let selectQuery = 'SELECT * FROM ?? WHERE ?? = ?';  
    let query = mysql.format(selectQuery,["users","username", req.body.username]);

    pool.query(query,(err, data) => {
        if(err) {
            console.error(err);
        }
        try {
            let match = bcrypt.compareSync(req.body.password, data[0].password)
            match ? token = generateToken(data[0]): token = null
          }
          catch (exception_var) {
           console.log('exception', exception_var)
          }
          finally {
            res.send(token)
          }
    })
})

function generateToken(data) {
    const secret = process.env.JWT_SECRET;
    console.log('inside generate token!', data)
    const payload = {
      data: data.username,
      //department: data.department,
      subject: data.id,
    };
    console.log(payload,'payload')
    const options = {
      expiresIn: "1d",
    };
    return jwt.sign(payload, secret, options);
    
  }
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

bcrypt.compare is an asynchronous function. So, you can use it in two ways. Use callback function or Use async await

 app.post("/login", jsonParser,(req, res) => { let selectQuery = 'SELECT * FROM ?? WHERE ?? = ?'; let query = mysql.format(selectQuery,["users","username", req.body.username]); pool.query(query, async (err, data) => { // Declare the function as async function if(err) { return console.error(err); } const match = await compare(req.body.password, data[0].password) // wait for the data from function const token = match ? generateToken(data[0]) : null res.send(token) }) })
over 4 years ago · Santiago Trujillo Denunciar
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