【问题标题】:Express-validator .getValidationResult()Express-validator .getValidationResult()
【发布时间】:2017-08-28 21:06:04
【问题描述】:

我正在为 Web 应用程序进行简单的登录,但似乎无法正确处理 .getValidationResult()。我花了很多时间翻阅 express-validator 的 npm 文档,试图在教程中找到答案,并在 Stack Overflow 之类的网站上寻找我的问题的答案。也许我只是不知道该问什么正确的问题。

我想确保

  1. 用户提交了电子邮件地址形式的内容,
  2. 密码不为空。然后我想
  3. 在稍后与数据库交互之前清理电子邮件,然后
  4. 检查前 3 个过程是否有任何失败。如果失败,将用户返回到登录页面。

我的问题是使用 express-validator 的.getValidationResult() 的正确方法是什么?

这是有问题的代码:

export let postLogin = (req: Request, res: Response, next: NextFunction) => {
  req.assert("email", "Email is not valid").isEmail();
  req.assert("password", "Password cannot be blank").notEmpty();
  req.sanitize("email").normalizeEmail({ gmail_remove_dots: false });

  req.getValidationResult().then(function(result){
      if (result != undefined) {
        console.log(result.array();
        return res.redirect("/login");
      }
    });

//do other login related stuff
}

我猜是一些简单的事情导致了我的错误,但我似乎找不到它是什么。

【问题讨论】:

  • 验证结果始终为!= undefined。它提供了对一个对象的访问,该对象有几种获取错误的方法。请参阅@turmuka 的回答。

标签: node.js typescript express express-validator


【解决方案1】:

它返回一个名为 Validation Object 的对象的承诺。此对象包含有关您的应用程序出现的错误的信息。

解释。

运行所有验证并返回验证结果对象 为同步和异步验证器收集的错误。

如果有错误,它所做的只是返回错误。这是该函数返回的一些示例代码。

//The error object

{
  "msg": "The error message",
  "param": "param.name.with.index[0]",
  "value": "param value",
  // Location of the param that generated this error.
  // It's either body, query, params, cookies or headers.
  "location": "body",

  // nestedErrors only exist when using the oneOf function
  "nestedErrors": [{ ... }]
}

当没有要显示的错误时,该函数返回isEmpty()

如果有任何错误,该函数将返回.array([options])。错误位于[options] 数组中。

查看this link 以了解它可能返回的示例代码。

更新

您也可以像这样使用它,这样更容易。
请注意,这是 express-validator v4.0.0 版本的新 API。

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

app.get('/myURL', (req, res, next) => {
      // Get the validation result\
      const errors = validationResult(req).throw();
      if (!errors.isEmpty()) {
        return res.status(422).json({ errors: errors }); //err.mapped() 
 });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-24
    • 2021-12-07
    • 2013-07-11
    • 2021-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多