I have the code (below) and one developer said to me that I had to validate my request:
router.post('/dashboard', passport.authenticate('jwt', { session: false }),
(req, res) => {
try {
let newPost = new Post({
category: req.body.category,
title: req.body.title,
photo: req.body.photo,
text: req.body.text,
author: req.body.author,
date: req.body.date
});
Post.addPost(newPost, (err, user) => {
if (err) {
res.json({success: false, msg: `Post has not been added. ${err}`})
} else {
res.json({success: true, msg: 'Post was added.'})
}
})
} catch (err) {
const error = (res, error) => {
res.status(500).json({
success: false,
message: error.message ? error.message : error
})
}
console.log('error routes/auth POST', res, error)
}
})
I google and found the solutions just with using libraries for request validation like express-validator - is it ok?
Isn't any native, built-in express, node.js methods to validate a request?
Or it's better to use library like express-validator?
CodePudding user response:
Express.js doesn't have a built-in validator. But you can use express-validator or joi. Both of these libraries are good.
if you are using typescript in your project class-validator is a better option, it will let you use types.
And this is a great talk on why you need to validate the data. Take Data Validation Seriously by Paul Milham