如何使用node-mssql查询SQL服务器错误[ERR_HTTP_HEADERS_SENT]?

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.")
        })                        
    }

})

错误:

_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...

一个请求不接受两个res,

  1. 所以我们在 res.send() 之前使用了 return 关键字, 所以它不会在代码中出现第二个 res
  2. 总是把 statement/code which return 放在你的特定代码 运行 之后,所以我改变了 transaction.commit() 的位置,把它放在 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 });
}