如何验证 Node.js 中的请求正文,Express - 是否可以不使用库?

How to validate request body in Node.js, Express - is it possible without using a library?

我有代码(如下),一位开发人员对我说我必须验证我的请求:

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)
    }
})

我 google 找到了使用像 express-validator 这样的库进行请求验证的解决方案 - 可以吗?

没有任何原生的、内置的快速 node.js 方法来验证请求吗?

或者使用像 express-validator 这样的库更好?

Express.js 没有内置验证器。 但是你可以使用express-validator or joi。这两个库都不错。

如果您在项目中使用打字稿 class-validator 是更好的选择,它会让您使用类型。

这是关于为什么需要验证数据的精彩演讲。 Take Data Validation Seriously by Paul Milham