【问题标题】:Express validator is not working with post value?Express 验证器不使用 post 值?
【发布时间】:2020-02-20 15:40:57
【问题描述】:

这是我当前的代码,它工作正常, 但是我需要在createValidationFor中访问req.body.type,如果我尝试访问代码req.body验证停止工作我不知道为什么

   router.post(
        '/login',
        createValidationFor('email'),
        checkValidationResult,
        (req, res, next) => {
            res.json({ allGood: true });
        } );

function createValidationFor(type) {

    switch (type) {
        case 'email':
            return [
                check('email').isEmail().withMessage('must be an email')
            ];

        case 'password':
            return [
                check('password').isLength({ min: 5 })
            ];
        default:
            return [];
    } }

function checkValidationResult(req, res, next) {
    const result = validationResult(req);
    if (result.isEmpty()) {
        return next();
    }

    res.status(422).json({ errors: result.array() }); }

修改后的代码:- 我正在尝试在 createValidationFor 函数中访问 req,但之后验证停止工作

router.post(
    '/login',
    createValidationFor,
    checkValidationResult,
    (req, res, next) => {
        res.json({ allGood: true });
    }
);

function createValidationFor(req, res) {
    var type = req.body.type;
    switch (type) {
        case 'email':
            return [
                check('email').isEmail().withMessage('must be an email')
            ];

        case 'password':
            return [
                check('password').isLength({ min: 5 })
            ];
        default:
            return [];
    }
}

function checkValidationResult(req, res, next) {
    const result = validationResult(req);
    if (result.isEmpty()) {
        return next();
    }

    res.status(422).json({ errors: result.array() });
}

【问题讨论】:

  • 我假设您想要的是首先检查电子邮件,然后检查密码是否匹配,就像我们如何进行 Microsoft 或 Google 登录一样?在这种情况下,我建议您将端点分开

标签: javascript express express-validator req


【解决方案1】:

您的函数createValidationFor 不应接收req, res, next 参数,因为它不是中间件,它只是根据type 值插入(返回)适当的验证链作为唯一需要的参数(在您的示例中为type = 'email' )。只有函数 checkValidationResult 负责所有中间件:如果存在验证错误,则发送错误或通过 next() 传递控制。

function createValidationFor (type) {
    switch (type) {
        case 'email':
            return [
                check('email').isEmail().withMessage('must be an email')
            ];
        case 'password':
            return [
                check('password').isLength({ min: 5 })
            ];
        default: 
            return [];
    };
};

function checkValidationResult(req, res, next) {
    const result = validationResult(req);
    if (result.isEmpty()) {
        return next();
    };
    res.status(422).json({ errors: result.array() });
};

router.post(
    '/login',
    createValidationFor('email'),
    checkValidationResult,
    (req, res, next) => {
        res.json({ allGood: true });
    }
);

【讨论】:

    猜你喜欢
    • 2014-08-05
    • 2019-09-01
    • 2020-11-07
    • 2016-11-17
    • 2022-07-16
    • 1970-01-01
    • 1970-01-01
    • 2019-12-05
    • 1970-01-01
    相关资源
    最近更新 更多