NodeJS Multer在上传之前验证字段 [英] NodeJS Multer validate fields before upload

查看:344
本文介绍了NodeJS Multer在上传之前验证字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试验证我的表单,然后再上传图像,但是我在中间件上得到的字符串为空

I'm trying to validation my form before i upload images but i getting empty string on my middleware

const upload = multer({
  storage: storage
});

router.post('/upload', formsValidation, upload.fields([{

  name: 'images',
  maxCount: 20

}, {

  name: 'imageMain',
  maxCount: 1

}]), function(req, res, next) {
  code...

});

这是我的中间件:

function formsValidation (req, res, next) {

  console.log(req.body) //getting empty array here
  return next();
}

我知道我可以使用multer中的fileFilter,但有时我没有任何图像可以上传,只是字符串要存储和验证,我试图将req.body从multipart/form-data解析为字符串,然后进行验证和使用next()但我收到范围错误,任何想法我该如何解决?

i know that i can use fileFilter from multer but some times i dont have any images to upload just string to store and validate, i have tried to parse the req.body from multipart/form-data to string then validate and use next() but i get a range error, any ideia how can i solve this?

推荐答案

这是来自Multer的文档 :

This is from Multer's docs:

请注意,req.body可能尚未完全填充.这取决于 按照客户端将字段和文件传输到服务器的顺序.

Note that req.body might not have been fully populated yet. It depends on the order that the client transmits fields and files to the server.

这意味着您必须在multer midlleware之后致电formsValidation,以确保所有发布的数据都已完全填充

That's mean you have to call formsValidation just after multer midlleware, to make sure that all posted data have been fully populated

router.post('/upload', upload.fields([{

    name: 'images',
    maxCount: 20

}, {

    name: 'imageMain',
    maxCount: 1

}]), formsValidation, function(req, res, next) {
    code...
});

这篇关于NodeJS Multer在上传之前验证字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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