最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

快递

运维笔记admin13浏览0评论

快递

快递

我想用快递验证来验证一些投入,但我有不同的设置比一个的文件中。

林验证如果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() });
       }
}

documentRoute

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

IM意识到检查本身就是一种中间件,让我怎么处理这个问题我现有的验证函数内可能收到一些其他验证。

目前,这是不行的,即使寿有效载荷被设置为null。它应该捕获错误并返回一个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。

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论