使用 Express-Validator 时如何向客户端返回 Multer 错误?

ska*_*kaz 5 javascript error-handling node.js multer express-validator

更新的帖子:滚动到帖子底部以获取更新的信息


原帖

我在这方面需要一些帮助。我正在创建一条采用 FormData 的路线,通过Multer验证文件数据(在本例中为图像),然后使用Express-Validator验证字符串数据。我已经创建了一个完成这两个验证的工作路线,但我不知道如何从Multer获取任何错误并将其返回给客户端。

我在Express-Validator之前设置了Multer ,以便Express-Validator可以读取 req.body 。这样,我不知道如何(或者我是否能够)传递Multer错误以在响应中发回。

我下面的示例应包括检查所需的所有内容,但如果您需要其他信息,请告诉我。

const multer = require('multer')
const {
    check,
    validationResult
} = require('express-validator/check');
const {
    sanitizeBody
} = require('express-validator/filter');


const imageUpload = multer({
    dest: 'uploads/',
    limits: {
        fileSize: 1000000
    },
    fileFilter: function (req, file, cb) {
        let filetypes = /jpeg|jpg/;
        let mimetype = filetypes.test(file.mimetype);
        let extname = filetypes.test(path.extname(file.originalname).toLowerCase());
        if (mimetype && extname) {
            return cb(null, true);
        }
        cb(new Error('Invalid IMAGE Type'))
    }
}).fields([{
        name: 'cover_image',
        maxCount: 1
    },
    {
        name: 'more_images',
        maxCount: 2
    }
])


const validationChecks = [
    check('street', 'Invalid Street Name').matches(/^[a-z0-9 ]+$/i).isLength({
        min: 1,
        max: 25
    }).trim().escape(),
    check('city', 'Invalid City Name').matches(/^[a-z ]+$/i).isLength({
        min: 1,
        max: 15
    }).trim().escape()
]


router.post('/addnewproperty', imageUpload, validationChecks,(req, res, next) => {  
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
        console.log('text validation FAILED');
        return res.status(400).json({
            errors: errors.array()
        });
    }
    console.log('validation PASSED');
})
Run Code Online (Sandbox Code Playgroud)

2019 年 2 月 6 日更新

好吧,我想我已经找到了解决方案,尽管不是我所期望的。

通过使用next()express中的函数,我可以在第一个路由处理程序中使用Multer,我可以在响应中接收和发回Multer错误。如果第一个路由处理程序中没有出现错误,我可以调用next(), 然后转到下一个路由处理程序以利用 Express-validator,在其中我可以检查并发送字符串验证中出现的任何错误。

下面的代码是我所描述内容的一个工作示例。不确定这是否是可接受的代码,但它正在进行一些简单的测试。对此有任何意见或建议欢迎在下面的评论中提出。


// Here's the meat of what I changed.  
// The config and variables set in the previous code are the same. 

router.post('/addnewproperty',(req, res, next) => {
    imageUpload(req,res,(err)=>{
        if(err){
            console.log(err.message);
            return res.status(400).json(err.message)
        }
        next()
    })
})

router.post('/addnewproperty',validationChecks,(req,res)=>{
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
        return res.status(400).json({
            errors: errors.array()
        });
    }
    return res.sendStatus(200)
})
Run Code Online (Sandbox Code Playgroud)

除了上面的代码之外,我将保留这个问题,以防有人有更好的解决方案来获得我最初打算做的事情。

Mad*_*ard 0

您可以通过直接调用中间件来获取错误,imageUpload而不是像在代码中那样在中间件链中使用它。

未经测试的片段,但希望至少能将您推向正确的方向:

router.post('/addnewproperty', validationChecks, (req, res, next) => {  
    const errors = validationResult(req);

    if (!errors.isEmpty()) {
        console.log('text validation FAILED');
        return res.status(400).json({
            errors: errors.array()
        });
    }

    imageUpload(req, res, (multerErr) => {
        if(multerErr){
            console.log('Multer validation FAILED');
            return res.status(400).json({
                errors: [multerErr.message]
            });
        }else{
            console.log('validation PASSED');
        }  
    });
})
Run Code Online (Sandbox Code Playgroud)

有关该主题的更多信息,请参阅有关错误处理的 Multer 官方文档