I am trying to send my token back to the client in the response of login. After 2 seconds my array called global gets populated with the token from my callback. However when I try to set it as a status I get this error. Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client. I've been struggling with this for two days now.
function findRow(x, callback) {
let selectQuery = 'SELECT * FROM ?? WHERE ?? = ?';
let query = mysql.format(selectQuery,["users","username", x.body.username]);
console.log('findrow', x.body.username)
pool.query(query, (err, data) => {
if(err) {
console.error(err);
}
console.log('tester')
match = bcrypt.compareSync(x.body.password, data[0].password)
console.log('match', match)
if (match){
token = generateToken(data[0]);
return callback(token)
} else {
console.log('invalid creds')
}
})
}
app.post("/login", async (req, res) => {
const global = []
findRow(req, function(token){
console.log('token login', token)
global.push(token)
})
setTimeout(function(){
---> res.sendStatus(200).json(global[0])
}, 3000);
})