node.js - 快速验证器将验证提取到单独的文件中

标签 node.js express express-validator

我正在尝试使用快速验证器验证某些输入,但我的设置与文档中的设置不同。

我正在验证 body.payload 是否不为空

this.validator.document

   public document = async (req: Request, res: Response, next: NextFunction) => {
        check("payload").exists({ checkNull: true });
        try {
            validationResult(req).throw();
            next();
          } catch (err) {
            res.status(422).json({ errors: err.mapped() });
        }
    }

this.controller.document

 public document = async (req: Request, res: Response): Promise<any> => {

        const errors = validationResult(req);
        if (!errors.isEmpty()) {
          return res.status(422).json({ errors: errors.array() });
       }
}

文档路由

     this.router.post("/:id/document",
            this.jwtGuard,
            this.validator.document,
            this.controller.document);

我知道检查本身就是一个中间件,所以我如何在现有的验证器函数中处理这个问题,该函数之前可能有一些其他验证。

目前这不起作用,即使有效负载设置为空。它应该捕获错误并返回 422 响应,但事实并非如此。

最佳答案

validator.document中:

public document = () => check("payload").exists({ checkNull: true });

documentRoute中:

this.router.post("/:id/document",
        this.jwtGuard,
        this.validator.document(), // notice the parentheses
        this.controller.document);

更新:如果要处理validator.document中的错误,需要在声明路由时在其前面调用check中间件:

this.router.post("/:id/document",
    this.jwtGuard,
    check("payload").exists({ checkNull: true }),
    this.validator.document,
    this.controller.document);

validator.document中:

public document = async (req: Request, res: Response, next: NextFunction) => {
   const errors = validationResult(req);
   if (!errors.isEmpty()) {
      return res.status(422).json({ errors: errors.array() });
   }
}

更新2:如果您有多个检查操作并且不想让您的路线定义变得臃肿,我建议您使用 schema validation .

关于node.js - 快速验证器将验证提取到单独的文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54577135/

相关文章:

javascript - 使用 Express-Validator 时如何向客户端返回 Multer 错误?

node.js - 数组作为参数传递给express post方法

Javascript 异步执行 : will a callback interrupt running code?

javascript - 无法访问 Azure Web App Linux 或 Windows 上的 NodeJS 站点

javascript - fetch-mock 调用实际的 API,而不是模拟请求

javascript - 您可以从同一个 Controller 内部调用两个 Promise 吗?

javascript - 如何将 HTTP header 发送到 Connect (Node.js) 中的静态目录

node.js - Windows 中的 Flightplan - 主机 key 验证失败

node.js - ExpressJS : Getting parsed and raw body simultaneously

javascript - 如何使用express-validator的黑名单方法