为什么我的响应呼叫超出范围并且不起作用? NodeJs、Bcrypt、Express、MySQL

我使用 Nodejs 和 MySQL 来验证用户密码。我很难访问我的响应 (res) 对象以将响应发送回客户端。出于某种原因,它可以在我的 bcrypt 函数上方运行,但不能在下方运行。我需要在下面访问它,以便我可以将我的 JWT 令牌发送回客户端。请参阅下面的代码示例。谢谢。

**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",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",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);
    
  }
zhangchengmao 回答:为什么我的响应呼叫超出范围并且不起作用? NodeJs、Bcrypt、Express、MySQL

bcrypt.compare 是一个异步函数。因此,您可以通过两种方式使用它。使用回调函数或使用异步等待

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)
    })
})
本文链接:https://www.f2er.com/961.html

大家都在问