'Error [ERR_HTTP_HEADERS_SENT] Express server crashing in node.js

So this code works fine and does everything, but continues to crash my express server. This is the error: node:internal/errors:464 ErrorCaptureStackTrace(err); ^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client at new NodeError (node:internal/errors:371:5) at ServerResponse.setHeader (node:_http_outgoing:576:11) at ServerResponse.header (C:\Users\user\dragonfitness\crud-application\server\node_modules\express\lib\response.js:776:10) at ServerResponse.send (C:\Users\user\dragonfitness\crud-application\server\node_modules\express\lib\response.js:170:12) at ServerResponse.json (C:\Users\user\dragonfitness\crud-application\server\node_modules\express\lib\response.js:267:15) at ServerResponse.send (C:\Users\user\dragonfitness\crud-application\server\node_modules\express\lib\response.js:158:21) at Request. (C:\Users\user\dragonfitness\crud-application\server\index.js:89:11) { code: 'ERR_HTTP_HEADERS_SENT'

app.post('/login', async (req, res)=>{
  try{
    var sql = "SELECT password FROM dbo.user_info WHERE user_name = @username"
    const request = new Request(sql,
      (err, result) => {
        if (err) {
          console.error(err.message)
        }
        if(result == 0){
          console.log("failed")
          return res.send({message: "Wrong username/password combination"})
        }
      }  
    );
    request.on('row', async function(columns) {
      console.log(columns)
      const password =columns[0].value;
      console.log(req.body.passwordlog)
      console.log(password)
    const isValid = await bcrypt.compare(req.body.passwordlog, password)
    if(isValid){
      console.log("passed")
      return res.send({message: "Login Sucessful"})
    }
    });
    request.addParameter('username', TYPES.NVarChar, req.body.usernamelog)
  
    connection.execSql(request);
  }catch{
    console.log("better not")
    return res.status(500).send()
  }
  });

the console.logs are working perfect and sends the request back to the front end just fine. and does what it's suppose to but it crashes my express server. Any help?



Solution 1:[1]

Return res.send() eveywhere

 return res.send({message: "Wrong username/password combination"})

and

return res.send({message: "Login Sucessful"})

You are trying to send response multiple times. Apply return to each and every res.send() statement and it will work fine.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1