[英]Express validator fails to validate data correctly
Hello i am using the latest version of express-validator to validate my requests body, the problem is when i am using notEmpty() or not().isEmpty() it always shows an error with prsonalized message i putted "text field is required" even when the text field is not empty this is my validator.js file您好,我正在使用最新版本的 express-validator 来验证我的请求正文,问题是当我使用 notEmpty() 或 not().isEmpty() 时,它总是显示我输入的私人消息错误“文本字段是必需的" 即使文本字段不为空,这也是我的 validator.js 文件
import { body } from "express-validator";
export const checkPost = () => {
return [
body("text")
.trim()
.notEmpty()
.withMessage("text field is required")
];
};
this is my route.js:这是我的 route.js:
router.post("/", checkPost(), uploadImg, createPost);
and this is my controller.js这是我的 controller.js
export const createPost = async (req, res) => {
try {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.json({ errors: errors.array() });
} ....
this is the response i get:这是我得到的回应:
{
"errors": [
{
"value": "",
"msg": "text field is required",
"param": "text",
"location": "body"
}
]
}
Can anyone help me please?任何人都可以帮助我吗?
You will need a body parser middleware set up before handling the body fields.在处理正文字段之前,您需要设置正文解析器中间件。 For instance, try setting your route like this (if you're sending the body as json):例如,尝试像这样设置您的路线(如果您将正文作为 json 发送):
router.post("/", express.json(), checkPost(), uploadImg, createPost);
After many hours of search i found that the express-validator middleware should be called after the usage of multer so changing my route this way solved the problem经过几个小时的搜索后,我发现应该在使用 multer 后调用 express-validator 中间件,因此以这种方式改变我的路线解决了问题
router.post("/",uploadImg, checkPost(), createPost);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.