I'm trying to create a module for my validation requests of req.body
.
instead of adding the following piece of code to every request to the server, I want to just add it to a module and do it in a one-line code.
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
So I have put this code in validation.js
:
const { validationResult } = require("express-validator");
// Finds the validation errors in this request and wraps them in an object with handy functions
const checkForErrors = (req, res, next) => {
console.log("hello");
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
};
module.exports = checkForErrors;
and this in app.js
:
const checkForErrors = require("../config/validation");
// get /business/biz/:id page
router.get(
"/biz/:id",
[param("id").isAlphanumeric().trim()],
(req, res) => {
checkForErrors(req,res);
bizID = req.params.id;
console.log(bizID);
res.send("Hello Business biz single page ");
}
);
But when I do this and there is an error I get Error can't send headers after they are sent
.
How can I make sure that if there is an error the response stops in validation.js
?
Thanks in advance.