I try use function:
exports.get = async function (req, res, next) {
filter.validateId(req,res,next);
const db = req.app.get('db');
let id = req.params.id;
let user;
try {
user = await db.models.user.findByPk(id);
} catch (err) {
res.send(400)
}
res.json(user);
};
and exported function:
var validateId = function (req, res, next) {
let id = parseInt(req.params.id);
if (isNaN(id) || id <= 0) {
res.send(400);
}
res.locals.id = id;
return next();
};
exports.validateId=validateId;
But I got error:
GET /users/203 404 17.862 ms - 90
(node:20775) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client at ServerResponse.setHeader (_http_outgoing.js:470:11) at ServerResponse.header (/home/qt/dev/BigDealExpressJSTest/node_modules/express/lib/response.js:767:10) at ServerResponse.send (/home/qt/dev/BigDealExpressJSTest/node_modules/express/lib/response.js:170:12) at ServerResponse.json (/home/qt/dev/BigDealExpressJSTest/node_modules/express/lib/response.js:267:15) at exports.get (/home/qt/dev/BigDealExpressJSTest/controllers/userController.js:28:7) (node:20775) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1) (node:20775) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Cannot set headers after they are sentis because you are sending a response twice, probably onvalidateIdfirst and later withres.json(user)- Daniel DobladoUnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1) (node:21582) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.- test123bigdeal