简体   繁体   English

主体错误不触发快速验证器

[英]Body errors not triggering express-validator

The validation middleware code is not triggered in the code I created, although all the logging flags are executed.尽管执行了所有日志记录标志,但我创建的代码中未触发验证中间件代码。

const { check, validationResult } = require("express-validator");

module.exports = {
    validateUsers(req, res, next) {
        if (req.method === "POST") {
            console.log(req.body.email);
            check(["email", "Must consist only of letters."]).isEmail();
        }

        const errors = validationResult(req);

        if (!errors.isEmpty()) {
            return res.json(errors);
        }  else {
            return next();
        }
    }
}

I've tried sending req and req.body with check , as well as using body with both options.我试过使用check发送reqreq.body ,以及将body与这两个选项一起使用。 Console logs show a non-email string supplied, and I've tried other fields and other (failing) values.控制台日志显示提供的非电子邮件字符串,并且我尝试了其他字段和其他(失败)值。

Can anyone point me in a helpful direction?谁能指出我有用的方向? I've used older versions with checkBody , but I'm stuck with these.我用过旧版本的checkBody ,但我坚持使用这些。 I've been fussing with app.js , but it's got no uncommented code right now.我一直在关注app.js ,但现在没有未注释的代码。

check returns a middleware, but you are not using this and passing the required args to it. check返回一个中间件,但您没有使用它并将所需的参数传递给它。

const { check, validationResult } = require("express-validator");

module.exports = {
    validateUsers(req, res, next) {
        if (req.method === "POST") {
            console.log(req.body.email);
            const middleware = check(["email", "Must consist only of letters."]).isEmail();
            middleware(req, res, next)
           
        }

        const errors = validationResult(req);

        if (!errors.isEmpty()) {
            return res.json(errors);
        }  else {
            return next();
        }
    }
}

I'd suggest though this is a little unergonomic.我建议虽然这有点不符合人体工程学。 It might not even work, because that middleware returned from check could call next, and then your code wouldn't make sense.它甚至可能不起作用,因为从check返回的中间件可能会调用 next,然后您的代码就没有意义了。 It's designed to be used differently.它旨在以不同的方式使用。 It'd probably be cleaner to do like:这样做可能会更干净:

const { body, validationResult } = require("express-validator");

module.exports = {
    validateUsers: [
            body(["email", "Must consist only of letters."]).isEmail(),
            (req, res, next) => {
                const errors = validationResult(req);

                if (!errors.isEmpty()) {
                    return res.json(errors);
                }  else {
                    return next();
                }
            }
        ]
}

And then use like:然后像这样使用:

app.post('/thing', validateUsers, (req, res, next) => {
   // you'd get here only if there were no issues
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM