【问题标题】:req.check is not function in express-validator?req.check 在 express-validator 中不起作用?
【发布时间】:2021-07-21 17:39:48
【问题描述】:

我正在验证密码的验证器页面。

exports.userSignupValidator = (req, res, next) => {
    // check for password
    req.check('password', 'Password is required').notEmpty();
    req.check('password')
        .isLength({ min: 6 })
        .withMessage('Password must contain at least 6 characters')
        .matches(/\d/)
        .withMessage('Password must contain a number');
    // check for errors
    const errors = req.validationErrors();
    // if error show the first one as they happen
    if (errors) {
        const firstError = errors.map(error => error.msg)[0];
        return res.status(400).json({ error: firstError });
    }
    // proceed to next middleware
    next();
};

我在其中定义注册路由并将 userSignupValidation 作为中间件来验证密码的路由页面。

router.post("/signup", userSignupValidator, async(req, res) => {
    const {name, email, password} = req.body;
    try{
        await User.findByCredentials(name, email, password);
        const user = new User({
            name,
            email,
            password
        })
        await user.save();
        res.send({message: "Successfully Registered"});
    }
    catch(e){
        res.status(422).send({error: e.message});
    }
})

为什么我得到 req.check 不起作用。

【问题讨论】:

  • 你用的是什么版本?对于较新版本的 check 和类似版本,需要/从 express-validator 导入,而不是从请求中执行。
  • 我正在使用新版本,但我不知道 req.check 在 express-validator 的第 6 版中不起作用。兄弟,你能写出适用于第 6 版 express-validator 的整个代码吗?
  • 查看文档,根据文档更新代码,如果有问题我可以尝试帮助解决。

标签: node.js express-validator


【解决方案1】:

此代码适用于第 6 版 express-validator。您可以查看 express-validator 的文档 -> https://express-validator.github.io/docs/migration-v5-to-v6.html

exports.userSignupValidator = async(req, res, next) => {
    // check for password
    await body('password', 'password is required').notEmpty().run(req)
    await body('password')
        .isLength({ min: 6 })
        .withMessage('Password must contain at least 6 characters').run(req)
    // check for errors
    const errors = validationResult(req);
    console.log(errors.errors);
    // if error show the first one as they happen
    if (!errors.isEmpty()) {
        const firstError = errors.errors.map(error => error.msg)[0];
        return res.status(400).json({ error: firstError });
    }
    // proceed to next middleware
    next();
};

【讨论】:

    【解决方案2】:

    有几件事会阻止您的代码正常工作,我还建议您在此解决方案之后查看express-validator docs,非常全面。所以让我们开始吧。

    Check 函数负责将您的验证规则添加到请求正文中,而validationResult 是负责执行并确保请求正文遵循此规则的函数。照这样说, 以下是解决问题的方法。

    因为你喜欢模块化,所以把你的验证规则写成这样的函数:

    uservalidation.js

    const { check, validationResult } = require("express-validator") 
    
    //this sets the rules on the request body in the middleware
    const validationRules = () => {
        return [
            check('password')
            .notEmpty()
            .withMessage('Password is required')
            .isLength({ min: 6 })
            .withMessage('Password must contain at least 6 characters')
            .matches(/\d/)
            .withMessage('Password must contain a number'),
            //you can now add other rules for other inputs here, like username, email...
            // notice how validation rules of a single field is chained and not seperated
        ]
    }
    
    //while this function executes the actual rules against the request body
    const validation =  ()  => {
        return (req, res, next) => {
            //execute the rules
            const errors = validationResult(req)
            // check if any of the request body failed the requirements set in validation rules
            if (!errors.isEmpty()) {
                // heres where you send the errors or do whatever you please with the error, in  your case 
                res.status(400).json{error:errors}
                return
            }
            // if everything went well, and all rules were passed, then move on to the next middleware
            next();   
        }
    }
    
    
    

    现在在你的实际路线中,你可以拥有这个

    userroute.js

    //import the functions declared above.
    const { validationRules, validation } = require("./uservalidation.js")
    
    // for your sign up route
    
    // call the validationRules function, followed by the validation
    router.post("/signup", validationRules(),validation(), async(req, res) => {
        const {name, email, password} = req.body;
        try{
            await User.findByCredentials(name, email, password);
            const user = new User({
                name,
                email,
                password
            })
            await user.save();
            res.send({message: "Successfully Registered"});
        }
        catch(e){
            res.status(422).send({error: e.message});
        }
    })
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-12
      相关资源
      最近更新 更多