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);
}
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) }) })