新的express-validator语法:验证multer处理的表单 [英] New express-validator syntax : validate form processed by multer

查看:343
本文介绍了新的express-validator语法:验证multer处理的表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在构建一个小型应用程序,以学习如何使用express.js.我有一个非常简单的表单,可以同时提交一个文本字段和一个文件.这是通过FormData提交的,因此我在后端使用multer处理请求.我想做的是对表单的文本输入之前进行验证,并对文件进行任何操作(即,仅在验证成功时保存,否则就不会发送某种错误消息). 我曾经那样做

So, I am building a small app in order to learn how to use express.js. I have a really simple form, submitting one text field and a file simultaneously. This is submitted through FormData, so I'm using multer on the back end to process the request. What I would like to do is perform a validation on the form's text input BEFORE taking any action concerning the file (i.e. save only if the validation succeeds, if not send some kind of error message). I used to do it that way

<form id="form" method='POST' enctype='multipart/form-data'>
      <input type='file' id='file-upload' name='file-upload' />
      <input type='text' id='text-upload' name='text-upload' />
      <input type='submit' />
</form>

后端: router.js

//somewhere in the router file
import {importedController} from './controllers/importedController';
/* some other routes */
router.post('/upload', importedController.processfunction);

importedController.js

exports.processfunction = (req, res, next) => {
var getFields = multer().any();
getFields(req, res, err => {
 if (err) {return next(err);}
 req.checkBody('text-upload','must not be empty!').notEmpty();
 //do the validation from here
 var errors = req.validationErrors();
 if (errors) { 
  //some logic
 } else {
  //some other stuff
  //in both, i can access req.body and req.file to do whatever i want
 }
});
}

但是我注意到似乎有用于快速验证器的新语法,所以我尝试遵循此语法并执行以下操作:

I noticed however that there seems to be a new syntax for express validator, so I tried to follow this syntax and to do:

router.js

router.post('/upload', [ body('text-input', 'must be not empty').not().isEmpty()], importedController.processfunction);

,但是然后在我的importatedController.js中,验证在我定义的multer getFields()函数之外不起作用(由于尚未处理请求,因此似乎很合逻辑).但是,如果我尝试将其包含在multer函数中:

but then in my importedController.js, the validation doesnt work outside of the multer getFields() function that I defined (seems logical since the request hasn't been processed yet). Yet, if I try to include it inside the multer function:

importedController.js

exports.processfunction = (req, res, next) => {
 var getFields = multer().any();
 getFields(req, res, err => {
  if (err) {return next(err);}
  errors = validationResult(req);
  if (!errors.isEmpty()) {
   //actually always yields and error...
  } else { //stuff}
 });
}

然后,尽管字段输入正确,但它总是返回错误.好像验证是在未处理" req上执行的,其中req.body为空.尽管该代码现在可以正常工作,所以不必着急,但是为了以后的项目,我想遵循新的语法. 任何帮助,不胜感激!

Then it always returns an error, although the field entry is correct. It is as if the validation was performed on the 'non processed' req, where req.body is empty. Although the code works now so there is no hurry, I would like to follow the new syntax for the sake of later projects. Any help greatly appreciated !

感谢@gustavohenke在下面的回答,我找到了一个解决方案

意识到,从根本上讲,我的问题与multer模块的工作方式有关,因为它似乎在处理表单数据之前必须先上载文件(必须在验证之前提交)-至少在multer模块看来使其无法控制何时上传文件,从而使您无法在实际保存文件之前调用其他中间件.

Realized that down to the core, my issue was linked to way the multer module works, since it seems to upload the file before it processes the form data (which must come before the validation) -- at least the multer module seems to give you no control on when it uploads the file, giving you no ability to call another middleware before actually saving it.

因此,我最终要做的是在客户端使用ajax首先仅将表单数据发送(保存文件供以后使用)到与表单验证器逻辑链接的multer().any()中间件中.根据第一次调用服务器的响应,然后将它与另一个ajax链接起来,最终将文件上传到另一条路由,这次使用multer(storage: myStorage).single('myFileInputName')来上传文件.

So what I ended up doing was using ajax on the client side to first send the form data only (saving the file for later), into a multer().any() middleware chained with the form validator logic. Depending on the response given by that first call to the server, I then chain it with another ajax to finally upload the file to another route, this time using a multer(storage: myStorage).single('myFileInputName') to upload the file.

考虑一下,此解决方案似乎比起初我想的要好:不仅避免输入格式错误的情况下保存文件,而且甚至避免使用任何带宽来发送文件(可以输入不正确.

Thinking about it, this solution seems perhaps better than what I thought about doing at first: not only does it avoid saving the file in case of bad form input, it even avoids using any bandwidth to send the file (that can be decently heavy) if the input is incorrect.

推荐答案

当您说验证是在multer处理尸体之前进行的时,您是正确的.

You're correct when you say that the validation took place before the body was processed by multer.

在两种情况下,验证器均应尽快运行;但请注意以下差异:

In both cases, the validators are run as soon as possible; but please note the following differences:

  • 在为旧版API提供的示例中,您在处理正文之后,在multer回调内定义验证 .因此,它有效.
  • 但是,在您的check API示例中,验证器是在 能够执行之前定义的,因此您总是会出错-req.body仍然为空.
  • In the example you gave for the legacy API, you define the validations within the multer callback, after the body was processed. Therefore, it works.
  • However, in your check API example, the validators are defined before multer has a chance to execute, so you'll always have errors - req.body is still empty.

这篇关于新的express-validator语法:验证multer处理的表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆