我正在使用快件-验证器,并且希望根据请求体中的值进行不同的检查。
我已经为此创建了一个函数,但我没有得到任何回复(即,快递只是挂起):
validation/profile.js
module.exports = function (req,res,next) {
if (req.body.type == 'teacher') {
return check('name').exists().withMessage('Name is required'),
} else {
return check('student_id').exists().withMessage('Student id is required'),
}
}app.js
router.put('/', require('./validation/profile'), (req, res, next) => {
const errors = validationResult(req).formatWith(errorFormatter)
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.mapped() })
} else {
res.send(req.user)
}
})但是,如果我将我的函数写成一个普通函数(而不是像中间件那样有3个params)并调用它,那么它都能工作。但是这样,我将无法访问请求对象。我得“硬编码”帕拉姆。
validation/profile.js
module.exports = function (type) {
if (type == 'teacher') {
return check('name').exists().withMessage('Name is required'),
} else {
return check('student_id').exists().withMessage('Student id is required'),
}
}app.js
router.put('/', require('./validation/profile')('teacher'), (req, res, next) => {
const errors = validationResult(req).formatWith(errorFormatter)
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.mapped() })
} else {
res.send(req.user)
}
})对于如何根据请求体中的值实现不同的检查,有什么建议吗?
发布于 2018-07-25 19:05:55
express-validator 检查API创建中间件,您应该将它直接附加到表达式中,或者像express那样自己调用它。
// Use routers so multiple checks can be attached to them.
const teacherChecks = express.Router();
teacherChecks.use(check('name').exists().withMessage('Name is required'));
const studentChecks = express.Router();
studentChecks .use(check('student_id').exists().withMessage('Student id is required'));
module.exports = function (req,res,next) {
if (req.body.type == 'teacher') {
teacherChecks(req, res, next);
} else {
studentChecks(req, res, next);
}
}您还可以使用oneOf来做同样的事情。
router.put('/', oneOf([
check('name').exists().withMessage('Name is required'),
check('student_id').exists().withMessage('Student id is required')
], 'Invalid request body'), (req, res, next) => {
const errors = validationResult(req).formatWith(errorFormatter)
if (
!errors.isEmpty()
) {
return res.status(422).json({errors: errors.mapped()})
}
else {
res.send(req.user)
}
});https://stackoverflow.com/questions/51525557
复制相似问题