Express Validator 使用 5.3.0 中间件功能

Express Validator using 5.3.0 middleware function

const app = require('express')();

const session = require('express-session');

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

app.use(session({
    secret: 'keyboard cat',
    resave: false,
    saveUninitialized: true,
    cookie: { secure: false }
}))
app.get("/test", [
    // username must be an email
    check('username').not().isEmpty(),`//.withCustomMessage() based on the content of req.session`
    // password must be at least 5 chars long
    check('password').not().isEmpty()
],(req,res)=>{
    console.log("req.session", req.session);
    // Finds the validation errors in this request and wraps them in an object with handy functions
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
        return res.status(422).json({ errors: errors.array() });
    }
    //console.log("req.session",req.session);
});

app.get("/",(req,res,next)=>{
  req.session.message  = "beoulo ";
 // console.log(req.session);
  res.status(200).json({
      "status" :"session set"
  });
});

app.listen(3000,()=>{
    console.log("Listening on port 3000!!!");
});

直接将 Check 作为中间件传递是使用它的唯一方法吗? 我们是否仍然可以在单独的中间件函数中使用 req.checkbody(field,errormessage) 格式或等效的格式,因为必须从会话

中获取错误消息

我想从 req.session 访问一个变量,并基于该变量生成一条自定义错误消息

之前的实现工作正常,因为它使用了 req.checkBody()

随着新的变化,我应该如何处理这种情况。

您可以在自己的处理程序中重写默认错误消息。

假设您的错误消息存储在 req.session.errors 中,并且这是一个将特定验证映射到特定错误消息的对象。

例如:

// req.session.errors =
{
  "USERNAME_EMPTY" : "The username cannot be empty",
  "PASSWORD_EMPTY" : "The password cannot be empty",
}

接下来,您将为每个验证提供与上述对象的键匹配的自定义消息:

check('username').not().isEmpty().withMessage('USERNAME_EMPTY')
check('password').not().isEmpty().withMessage('PASSWORD_EMPTY')

最后,在您的处理程序中,您执行从验证错误到错误消息值的查找:

if (! errors.isEmpty()) {
  const list = errors.array();

  list.forEach(error => {
    error.msg = req.session.errors[error.msg] || error.msg;
  });

  return res.status(422).json({ errors: list });
}

或者只依赖旧版本的 express-validator,这样您就可以继续使用旧版本 API。