【发布时间】: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