Express Validator使用5.3.0中间件功能


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.checkody(字段,错误消息(格式或类似的格式,因为错误消息必须从会话中获取

我想访问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。

最新更新