I am building a Node.js app using express, which I wanted to improve with express-validator. This is my first time with express-validator and I don't understand the warnings it causes. Its documentation is also not really verbose.
Here is a simplified version of a segment before I added the validation, the database calls have been replaced by sending a response back with the entry_id from the GET request.
router.get(
'/list_entries',
function (req, res, next) {
res.send(req.query.entry_id)
}
)
I added validation to check if entry_id is given in req.query and is in the valid range.:
router.get(
'/list_entries',
query('entry_id').isInt({ min: 1 }),
function (req, res, next) {
const errors = validationResult(req)
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() })
}
res.send(req.query.entry_id)
}
)
It seems to function well, in case of out of range values the errors do get displayed.
However, this also triggered a warning in typescript stating:Object is possibly 'undefined' referring to req.query in the response. I don't have a clear understanding how does the validation cause this, and how can I overcome it (other than using optional chaining like req.query?.entry_id). I wonder where I can find some documentation or working examples to enlighten me. Thanks in advance!
Your problem has little to do with Express Validator and is just Typescript being careful.
It has reasoned that it cannot prove (at compile-time) that req.query is defined, so it is warning you req.query.entry_id might cause a TypeError at run-time.
The simplest solution is to write this:
res.send(req.query?.entry_id)
which is simply shorthand for:
res.send(req.query === undefined ? undefined : req.query.entry_id)
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