req.проверка не работает в экспресс-валидаторе?

#node.js #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();
};
 

страница маршрута, на которой я определяю маршрут регистрации и использую проверку подписи пользователя в качестве промежуточного программного обеспечения для проверки пароля.

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

Почему я получаю запрос.проверка не является функцией.

Комментарии:

1. Какую версию вы используете? С более новыми версиями check и аналогичными требуется/импортируется из express-validator , а не выполняется из запроса.

2. Я использую новую версию, но я не знал, что проверка req.не будет работать в 6-й версии экспресс-валидатора. Братан, пожалуйста, напиши весь код, который будет работать с 6-й версией экспресс-валидатора.

3. Просмотрите документацию, обновите свой код на основе документации, если у вас есть проблемы, я могу попытаться помочь их решить.

Ответ №1:

Есть пара вещей, которые мешают вашему коду работать должным образом, я также посоветую вам после этого решения ознакомиться с документами экспресс-валидатора, довольно исчерпывающими. Так что давайте приступим к делу.

Функция проверки отвечает за добавление ваших правил проверки в тело запроса, в то время как функция 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});
    }
})

 

Ответ №2:

Этот код будет работать с 6-й версией экспресс-валидатора. Вы можете ознакомиться с документацией экспресс-валидатора -> >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();
};