req.check 在 express-validator 中不起作用?

req.check is not function in express-validator?

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

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 不是功能。

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

Check function is in charge of adding your validation rules to the request body, while the validationResult is the function in charge of executing and ensuring that the request body body follows this rules. With that said, Here is how you would solve your problem.

因为你喜欢模块化,所以在一个函数中编写你的验证规则:

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

此代码适用于 express-validator 的第 6 版。您可以查看 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();
};