首页 > 解决方案 > 在通过 multer 上传图像之前验证表单数据

问题描述

我正在使用 multer 将图像上传到我的服务器。我使用 express-validator 进行字段验证。我将数据作为多部分/表单数据发送。在图片上传之前,我想验证所有字段验证是否已执行,然后我上传图片,但是当我发送数据并记录它时,正文为空,但图片上传正文后有数据

这行得通

    routes.post('/register', upload.single('profile_pic'), validateSignup, signup)

但这未能提供数据

routes.post('/register', validateSignup, upload.single('profile_pic'), signup)

这是我的验证文件

module.exports = {

    email: {
        in: ['body'],
        errorMessage: 'Please enter a valid email address',
        exists: true,
        isEmail: {
            errorMessage: 'Invalid email format'
        }
    },
    password: {
        in: ['body'],
        isLength: {
            errorMessage: 'Password should be at least 6 chars long',
            options: { min: 6 }
        },
        matches: {
            options: [/^(?=.*[A-Z])/],
            errorMessage: 'At least has a upper letter'
        },
        exists: true
    },
    fullName: {
        in: ['body'],
        errorMessage: 'Please enter a your full name',
        isLength: {
            options: { min: 3, max: 50 }
        },
        exists: true
    }
}

也可以将 multer 用作函数而不是中间件,因为如果它是一个函数,我可以在任何地方调用它

标签: node.jsexpressmulter

解决方案


推荐阅读