Learning ExpressJS here.
I have a get
route that expects query params i.e.
app.get('/api', (req, res) => {
res.send({ name: req.query.name, age: req.query.age, club: req.query.club })
})
On postman the following http://localhost:5000/api?name=Messi&age=31&club=Barcelona
returns 200 with the res.body as:
{
"name": "Messi",
"age": "31",
"club": "Barcelona"
}
Question
How could I write a custom validation where:
You can build an easy validation middleware.
function validateQuery(fields) {
return (req, res, next) => {
for(const field of fields) {
if(!req.query[field]) { // Field isn't present, end request
return res
.status(400)
.send(`${field} is missing`);
}
}
next(); // All fields are present, proceed
};
}
app.get('/api', validateQuery(['name', 'age', 'club']), (req, res) => {
// If it reaches here, you can be sure that all the fields are not empty.
res.send({ name: req.query.name, age: req.query.age, club: req.query.club })
})
You can also use a third party module for validating requests.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With