0

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);
}) 
Shadow
  • 33,525
  • 10
  • 51
  • 64
  • Does this answer your question? [Error: Can't set headers after they are sent to the client](https://stackoverflow.com/questions/7042340/error-cant-set-headers-after-they-are-sent-to-the-client) – Đăng Khoa Đinh Aug 02 '21 at 17:36
  • Thats a realy bad design you have there. You should send the response asap as you received the data and avoid that `setTimeout` call. (or if the delay is needed) encapsulated the callbacks. To your question: https://expressjs.com/de/api.html `res.sendStatus` and `.json` sets both contentype header. BUT sendStatus does exactly what it should do, it sends the http header to the client. Therefor .json cant set/send the headers again. Use `res.status` to set the http status code. – Marc Aug 02 '21 at 18:19

0 Answers0