Multer 和快速验证器在验证中造成问题

Ami*_*mar 7 node.js express multer express-validator

我正在提交带有图像的表格。使用下面的代码。

router.post("/", upload.upload('image').single('categoryLogo'), categoryRules.categoryCreationRules(), validate, categoryController.createCategory);
Run Code Online (Sandbox Code Playgroud)

它工作正常,但是需要进行一些验证,然后静态图像才会保存在磁盘中。所以我尝试的是:

router.post("/", categoryRules.categoryCreationRules(), validate,upload.upload('image').single('categoryLogo'), categoryController.createCategory);
Run Code Online (Sandbox Code Playgroud)

但在这个快速验证器中得到空白主体,因此它经常抛出验证错误。我应该做什么,我在谷歌上搜索,但没有找到任何有用的信息,我是节点中的新手。

规则代码:

const categoryCreationRules = () => {

    return [
        check('name')
            .isLength({ min: 1 })
            .trim()
            .withMessage("Category name is required."),
        check('name').custom((name)=>{
             return CategoryModel.findOne({name: name}).collation({locale:'en',strength: 2})
                    .then(category=>{
                        if(category){
                            return Promise.reject(category.name+" category already exsist.");
                        }
                    })
        }),    
        check('name')
            .isLength({max: 100})
            .trim()
            .withMessage("Category name should not exceed more then 100 characters."),
        check('description')
            .isLength({max: 255})
            .trim()
            .withMessage("Category description should not exceed more then 255 characters.")
    ];
}
Run Code Online (Sandbox Code Playgroud)

Lui*_*nto 4

理论上来说,之前的运行categoryCreationRulesvalidate中间件multer就足够了。因此,您只需要在请求正文中进行验证,如果它包含任何错误,您只需返回错误的请求响应,而不让请求传递到下一个中​​间件(在本例中为 multer)。

\n

一个简单的例子我正在谈论的内容:(只是为了清楚起见,下面的代码将不起作用

\n
router.post("/", categoryRules.categoryCreationRules(), validate, upload.upload(\'image\').single(\'categoryLogo\'), categoryController.createCategory);\n\n\nconst validator = (req, res, next) => {\n  try {\n    validationResult(req).throw();\n\n    // Continue to next middleware, in this case, multer.\n    next();\n  } catch (errors) {\n    // return bad request\n    res.status(400).send(errors);\n  }\n};\n
Run Code Online (Sandbox Code Playgroud)\n

这不会\xc2\xb4t工作,因为你的req.body将是未定义的,因为你将数据作为a发送multipart/form-data(通常用于上传文件)。在这种情况下,错误将永远是正确的。

\n

但使用 multer 就不会发生这种情况 - 您将能够访问主体字段,例如descriptionname然后执行验证代码。

\n

发生这种情况是因为 multer 在内部使用名为Busboy 的库解析multipart/form-data请求,这样您就可以通过 req.body 访问字段。body

\n

因此,我认为最好的方法是在验证中间件之前调用 multer 中间件:

\n
router.post("/", upload.upload(\'image\').single(\'categoryLogo\'), categoryRules.categoryCreationRules(), validate, categoryController.createCategory);\n
Run Code Online (Sandbox Code Playgroud)\n

之后,如果验证出现错误,您可以删除从 multer 创建的文件并返回响应bad request,如下所示:

\n
const fs = require("fs");\n\nconst validator = (req, res, next) => {\n  try {\n    validationResult(req).throw();\n\n    // continue to next middleware\n    next();\n  } catch (errors) {\n    fs.unlink(req.file.path, (err) => {\n      if (err) {multipart/form-data\n        /* HANLDE ERROR */\n      }\n      console.log(`successfully deleted ${req.file.path}`);\n    });\n\n    // return bad request\n    res.status(400).send(errors);\n  }\n};\n\n
Run Code Online (Sandbox Code Playgroud)\n

您可以在以下链接中获取有关此内容的更多信息:

\n

node-js-with-express-bodyparser-无法从请求后获取表单数据

\n

请求主体未定义多部分

\n

html-multipart-form-data-error-in-req-body-using-node-express

\n