Agrego un validador así:
validate: (req, res, next) => { req.sanitizeBody("email").normalizeEmail({ all_lowercase: true}).trim(); req.check("password", "Password cannot be empty").notEmpty(); // Collect the results of previous validations. console.log(req.getValidationResult()); req.getValidationResult().then((error) => { if (!error.isEmpty()) { req.skip = true; res.locals.redirect = "/route1"; next(); } else { next(); // Call the next middleware function. } }); }y en las rutas tengo lo siguiente:
route.post("/route2", controller.validate, controller.save, controller.redirectView);la acción de guardar permite guardar un estudiante en mi base de datos (mongodb):
save : (req, res, next) => { if (req.skip) next() ; let student = { email : req.body.email, password : req.body.password, zipCode : req.body.zipCode }; const newStudent = new Student(student); newStudent .save() // method .then((student) => { res.locals.redirect = "/students"; res.locals.student = student; next(); }) .catch(error => { next(error); }); }y redirectView para representar una vista.
redirectView : (req, res, next) => { const redirectPath = res.locals.redirect; if(redirectPath) res.redirect(redirectPath); next(); },La validación funciona (creo que en caso de error, se ejecuta redirectView y se omite la acción de guardar), pero veo en la terminal:
Promise { <pending> } ERROR occurred: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client at new NodeError (node:internal/errors:371:5) at ServerResponse.setHeader (node:_http_outgoing:576:11) at ServerResponse.header (myapplicationPath\node_modules\express\lib\response.js:767:10)....
y tengo en otro archivo el siguiente código:
exports.pageError = (req, res) => { let errorCode = httpStatus.NOT_FOUND; res.status(errorCode); res.render("error"); };No puedo entender dónde está mi error.