express-validator v4 校验函数中访问请求体

Access request body in check function of express-validator v4

我刚开始使用 express.js 和 express-validator 来验证一些输入数据,我在访问 4.0.0 版中引入的新检查 API 中的请求正文时遇到问题。

在旧版本中,您只需将 express-validator 作为中间件添加到 app.js 中 body-parser 之后的某处:

// ./app.js
const bodyParser = require("body-parser");
const expressValidator = require("express-validator");

const index = require("./routes/index");

const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(expressValidator());

然后在我的索引路由中,我可以检查 post 方法的最终回调函数中的字段。

// ./routes/index.js
const express = require("express");
const router = express.Router();

router.post("/submit", (req, res, next) => {
    // check email
    req.check('email','Invalid email address').isEmail()
    // check if password is equal to password confirmation
    req.check('password', 'Invalid password')
    /* Access request body to compare password 
    field with password confirmation field */
    .equals(req.body.confirmPassword)

    // get errors
    const errors = req.validationErrors();

    // do stuff
});

就像在这个例子中,我可以很容易地检查我的密码字段和我的表单的密码确认字段的值是否相等。但是,从版本 4 开始,他们有一个新的 API,它要求您直接在路由器文件中加载 express-validator,并在 post 方法中的最终回调之前将检查函数作为函数数组传递,像这样:

// ./routes/index.js
const express = require("express");
const router = express.Router();
const { check, validationResult } = require("express-validator/check");

router.post(
    "/submit",
    [
        // Check validity
        check("email", "Invalid email").isEmail(),
        // Does not work since req is not defined
        check("password", "invalid password").isLength({ min: 4 })
        .equals(req.body.confirmPassword) // throws an error
    ],
    (req, res, next) => {
    // return validation results
    const errors = validationResult(req);

    // do stuff
});

这不起作用,因为未定义请求。所以我的问题是:如何访问 check() 链中的请求对象以将两个不同的字段与新的快速验证器 API 进行比较?非常感谢!

在摸索了一段时间后,我找到了一种通过使用自定义验证器来实现这一点的方法。传递给自定义方法的验证器函数接受一个包含请求主体的对象:

router.post(
    "/submit",
    [
    // Check validity
    check("email", "Invalid email").isEmail(),
    check("password", "invalid password")
        .isLength({ min: 4 })
        .custom((value,{req, loc, path}) => {
            if (value !== req.body.confirmPassword) {
                // trow error if passwords do not match
                throw new Error("Passwords don't match");
            } else {
                return value;
            }
        })
    ],
    (req, res, next) => {
        // return validation results
        const errors = validationResult(req);

        // do stuff
    });