0

这是我当前的代码,它工作正常,但是我需要在 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() });
}
4

1 回答 1

0

您的函数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 });
    }
);
于 2019-10-31T15:33:48.353 回答