node.jssql-serverexpressnode-mssql

How to use node-mssql query SQL Server Error [ERR_HTTP_HEADERS_SENT]?


const request = new sql.Request(transaction)
request.query('select * from TB_USER', (err, result) => {
    if (err) {                            
        res.send(err);
        transaction.rollback(err => {
            console.log("Transaction RolledBack.")
        })
    }
    else{
        res.status(200).json({"result":result.recordsets})
        transaction.commit(err => {
            console.log("Transaction committed.")
        })                        
    }

})
const request1 = new sql.Request(transaction)
request1.query('select * from TB_USER', (err, result) => {
    if (err) {                            
        res.send(err);
        transaction.rollback(err => {
            console.log("Transaction RolledBack.")
        })
    }
    else{
        res.status(200).json({"result":result.recordsets})
        transaction.commit(err => {
            console.log("Transaction committed.")
        })                        
    }

})

Error:

_http_outgoing.js:536
throw new ERR_HTTP_HEADERS_SENT('set');
^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

at ServerResponse.setHeader (_http_outgoing.js:536:11)
at ServerResponse.header (A:\register-api\node_modules\express\lib\response.js:771:10)
at ServerResponse.send (A:\register-api\node_modules\express\lib\response.js:170:12)
at ServerResponse.json (A:\register-api\node_modules\express\lib\response.js:267:15)
at A:\register-api\src\utils\functions\updateCust.js:15:33 at A:\register-api\node_modules\mssql\lib\base\request.js:446:9 at Request.userCallback (A:\register-api\node_modules\mssql\lib\tedious\request.js:479:15) at Request.callback (A:\register-api\node_modules\tedious\lib\request.js:206:14) at Parser.onEndOfMessage (A:\register-api\node_modules\tedious\lib\connection.js:2902:22) at Object.onceWrapper (events.js:420:28) { code: 'ERR_HTTP_HEADERS_SENT' } [nodemon] app crashed - waiting for file changes before starting...


Solution

  • One request doesn't accept two res,

    1. So we used return keyword before res.send() , So It won't go for second res in the code.
    2. Always put statement/code which return something after your sepcific code run, So I changed position of transaction.commit() and put it before return res.send().
    if (err) {
      transaction.rollback((err) => {
        console.log("Transaction RolledBack.");
      });
      return res.send(err);
    } else {
      transaction.commit(() => {
        console.log("Transaction committed.");
      });
      return res.status(200).json({ result: result.recordsets });
    }