I know this question has been asked a lot but none of the answers served my case. I keep getting this error even though I send a response to client only once. Please could anyone point to me what I'm missing? I appreciate any help. Here is my router code:
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()
}
})
})
})
here is the error log:
throw err; // Rethrow non-MySQL errors ^
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client at ServerResponse.setHeader (_http_outgoing.js:526:11) at ServerResponse.header (/Users/diego/Documents/DT Personal Training App/express-api/node_modules/express/lib/response.js:771:10) at ServerResponse.send (/Users/diego/Documents/DT Personal Training App/express-api/node_modules/express/lib/response.js:170:12) at ServerResponse.json (/Users/diego/Documents/DT Personal Training App/express-api/node_modules/express/lib/response.js:267:15) at Query. (/Users/diego/Documents/DT Personal Training App/express-api/routes/admin/trainers.js:53:36) at Query. (/Users/diego/Documents/DT Personal Training App/express-api/node_modules/mysql/lib/Connection.js:526:10) at Query._callback (/Users/diego/Documents/DT Personal Training App/express-api/node_modules/mysql/lib/Connection.js:488:16) at Query.Sequence.end (/Users/diego/Documents/DT Personal Training App/express-api/node_modules/mysql/lib/protocol/sequences/Sequence.js:83:24) at Query.ErrorPacket (/Users/diego/Documents/DT Personal Training App/express-api/node_modules/mysql/lib/protocol/sequences/Query.js:92:8) at Protocol._parsePacket (/Users/diego/Documents/DT Personal Training App/express-api/node_modules/mysql/lib/protocol/Protocol.js:291:23) { code: 'ERR_HTTP_HEADERS_SENT' }
return res.sendStatus(500).json({error: err})toreturn res.status(500).json({error: err})I suspectsendStatusis sending headers and closing connection before sendingcontent-typeheaders (forjsonmethod) - num8erconst numPerPage = parseInt(req.params.limit); const page = parseInt(req.params.page);- num8er