【问题标题】:multer and express-validator error handlingmulter 和 express-validator 错误处理
【发布时间】:2020-01-03 19:24:24
【问题描述】:

我正在尝试使用 multer 验证包含图像的表单,使用 express-validator 验证包含其他字段的表单,但在发布路由中总是出现未定义的错误 (req.validationError),有什么解决方案吗?

server.js

const express = require('express');
const { check, validationResult  , body} = require('express-validator');
var mkdirp = require('mkdirp');
var fs = require('fs-extra');
const path = require('path');
const multer = require('multer');
const cors = require('cors');
const morgan = require('morgan');
var rezizeimg = require('resize-img');
var adminrouter = express.Router();

adminrouter.post('/add_products',[check('description','description should not be empty ').notEmpty(),
        check('title','title should not be empy').notEmpty(),
        check('price','price should not be empty ').isDecimal()



],  (req,res)=> {
    let upload = multer({storage: storage, fileFilter: helpers.imageFilter}).single('profile_pic');

    upload(req, res, function (err) {
        // req.file contains information of uploaded file
        // req.body contains information of text fields, if there were any

        if (req.fileValidationError) {
            console.log(req.fileValidationError);
            return res.send(req.fileValidationError);
        } else if (!req.file) {
            filerror = 'Please select an image to upload';
        } else if (err instanceof multer.MulterError) {
            console.log(err);
            filerror = err;


        } else if (err) {
            console.log(err);
            return res.send(err);

        }



helpers.js

const imageFilter = function(req, file, cb) {
    // Accept images only
    if (!file.originalname.match(/\.(jpg|JPG|jpeg|JPEG|png|PNG|gif|GIF)$/)) {
        req.fileValidationError = 'Only image files are allowed!';
        return cb(new Error('Only image files are allowed!'), false);
    }
    cb(null, true);
};
exports.imageFilter = imageFilter;

【问题讨论】:

    标签: javascript node.js express multer express-validator


    【解决方案1】:

    如果文件不是图像,您的助手似乎只会将 fileValiditionError 字段附加到请求中。因此,如果您要上传有效图像,则请求中不会有 fileValiditionError 字段。您应该只检查上传函数返回的错误。如果有错误,您可以向客户端返回错误消息

    【讨论】:

    • 嗨,即使文件不是图像,req.validationError 总是未定义?
    • 你是否将你的辅助函数导入到 server.js 文件中?
    • 是的,我认为 body-parser 不再支持 multipart 所以我必须使用 busboy 或 multiparty
    猜你喜欢
    • 2017-10-25
    • 1970-01-01
    • 1970-01-01
    • 2016-09-14
    • 2020-12-17
    • 2021-11-28
    • 2019-06-29
    • 1970-01-01
    • 2023-02-17
    相关资源
    最近更新 更多