I add a validator like that:
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.
}
});
}
and in the routes I have the following:
route.post("/route2", controller.validate, controller.save, controller.redirectView);
the save action allows to save a student in my database (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);
});
}
and redirectView to rendrer a view.
redirectView : (req, res, next) => {
const redirectPath = res.locals.redirect;
if(redirectPath) res.redirect(redirectPath);
next();
},
The validation works (I think since in case of error, the redirectView is executed and the save action is skipped.) but I see in the 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)
....
and I have in another file the following code:
exports.pageError = (req, res) => {
let errorCode = httpStatus.NOT_FOUND;
res.status(errorCode);
res.render("error");
};
I cannot usderstand where is my error.