Express API:错误[ERR_HTTP_HEADERS_SENT]

我知道这个问题已经问了很多,但没有一个答案适合我的情况。 即使我仅向客户端发送一次响应,我仍会收到此错误。请任何人指出我所缺少的东西吗?感谢您的帮助。这是我的路由器代码:

router.get("/trainers/:page/:limit", verifyToken, (req, res) => {

  const numPerPage = req.params.limit; // number of items per page
  const page = req.params.page;
  let result; //final object to be sent to client

  connection.query("Select count(*) as totalCount from trainers", (err, rows, fields) => {
    if (err) {
      return res.sendStatus(500).json({error: err})
    }
    var totalCount = rows[0].totalCount;
    var numPages = Math.ceil(totalCount / numPerPage);

    connection.query("SELECT id FROM trainers LIMIT ? OFFSET ?", [numPerPage, (page-1) * numPerPage], (err, rows, fields) => {
      if (err) {
        return res.sendStatus(500).json({error: err})
      } else {
        result = { rows, numPages }
        res.json()
      }
    })
  })
})

这是错误日志:

抛出错误//抛出非MySQL错误       ^

错误[ERR_HTTP_HEADERS_SENT]:将标头发送到客户端后无法设置标头     在ServerResponse.setHeader(_http_outgoing.js:526:11)     在ServerResponse.header(/ Users / diego / Documents / DT Personal Training App / express-api / node_modules / express / lib / response.js:771:10)     在ServerResponse.send(/ Users / diego / Documents / DT Personal Training App / express-api / node_modules / express / lib / response.js:170:12)     在ServerResponse.json(/ Users / diego / Documents / DT Personal Training App / express-api / node_modules / express / lib / response.js:267:15)     在查询。 (/用户/ diego /文档/ DT个人培训应用程序/express-api/routes/admin/trainers.js:53:36)     在查询。 (/用户/ diego /文档/ DT个人培训应用程序/express-api/node_modules/mysql/lib/Connection.js:526:10)     在Query._callback(/ Users / diego / Documents / DT Personal Training App / express-api / node_modules / mysql / lib / Connection.js:488:16)     在Query.Sequence.end(/ Users / diego / Documents / DT Personal Training App / express-api / node_modules / mysql / lib / protocol / sequences / Sequence.js:83:24)     在Query.ErrorPacket上(/ Users / diego / Documents / DT Personal Training App / express-api / node_modules / mysql / lib / protocol / sequences / Query.js:92:8)     在Protocol._parsePacket(/ Users / diego / Documents / DT Personal Training App / express-api / node_modules / mysql / lib / protocol / Protocol.js:291:23){   代码:“ ERR_HTTP_HEADERS_SENT” }

评论