问题描述
我试图使用快速验证器库添加验证。现在我厌倦了将所有检查调用转储到我的路由文件中,并创建了一个新文件来将它们全部存储在 middleware/validator.js 中。当我访问 post profileController.createOne 时,我的验证中间件通过失败并返回适当的 json 错误而按预期工作,但是当我访问 profileController.searchForProfile 端点时,express 跳过验证并直接转到控制器并抛出以下错误而不是包含缺失字段的预期 json 错误
UnhandledPromiseRejectionWarning:错误:WHERE 参数“firstname” 具有无效的“未定义”值
我添加了一些断点来测试 searchForProfileValidationRules 是否曾经被调用过并且从未被访问过。关于我做错了什么的任何想法?
const { check,validationResult } = require('express-validator')
const profileCreateValidationRules = () => {
return [
check('firstname').exists().isstring(),check('lastname').exists().isstring(),check('dob').exists().isDate(),check('gender').exists().isLength({ max: 6 }),//Todo set to limited options
check('martial_status').exists(),//Todo set to limited options
check('phone_no').exists().isMobilePhone(),//Todo set to phone
check('next_of_kin_name').exists().isstring(),check('CityId').exists().isInt(),check('StateId').exists().isInt(),check('CountryId').exists().isInt(),]
}
const searchForProfileValidationRules = () => {
return [
check('firstname').exists().isstring(),check('dob',"Enter a valid date").exists().isDate(),]
}
const validate = (req,res,next) => {
const errors = validationResult(req)
if (errors.isEmpty()) {
return next()
}
const extractedErrors = []
errors.array().map(err => extractedErrors.push({ [err.param]: err.msg }))
return res.status(422).json({
status: "error",errors: extractedErrors,})
}
module.exports = {
searchForProfileValidationRules,profileCreateValidationRules,validate,}
路由文件
const profileController = require('../controllers/profile.controller');
const { searchForProfileValidationRules,validate } = require('../middlewares/validators');
const router = require('express').Router();
//CRUD Model-Agnostic.
//Keep them at the end of the route file for url parsing requests
router
.get('/',profileController.getmine)
.get('/search',searchForProfileValidationRules(),profileController.searchForProfile)
.get('/:userId',profileController.getone)
.post('/',profileCreateValidationRules(),profileController.createOne)
.put('/:id',profileController.updateOne)
.delete('/:id',profileController.deleteOne);
module.exports = router;
控制器文件片段。正如预期的那样,当未提供查询参数时,express 会抛出有关缺少字段的错误
// Find a single Profile with an name,and dob
exports.searchForProfile = async (req,res) => {
let user_details = await Profile.findOne({ where: { 'firstname': req.query.firstname,'lastname':req.query.lastname,'dob':req.query.dob} });
return res.json(user_details);
};
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)