【问题标题】:verify request body before uploading file using multer在使用 multer 上传文件之前验证请求正文
【发布时间】:2018-09-19 17:23:17
【问题描述】:

我目前正在使用 nodejs 开发 API。我希望用户上传文件以及其他所需的详细信息。但问题是 multer 在我能够验证用户传递的所需详细信息之前上传文件。有没有办法只在 req.body 值验证后才上传文件?

我当前的代码:

router.post("/", upload.single("gallery_item_image"), function (req, res, next) {
    Branch
        .findById({ _id: req.body.branch_id })
        .exec()
        .then((doc) => {
            if(!doc || req.body.branch_id.length < 24) {
                return res.status(404).json({
                    message: "Invalid Branch ID",
                })
            }
            galleryItem = new GalleryItem({
                _id: mongoose.Types.ObjectId(),
                branch_id: req.body.branch_id,
                caption: req.body.caption,
                description: req.body.description,
                absoluteImagePath: req.file.path,
                imagePath: "some.url"
            })
            return galleryItem.save()
        })
        .then((response) => {
                console.log(response);
                res.status(201).json({
                    message: "Gallery item successfully added to the database",
                    galleryItem: {
                        _id: response._id, 
                        branch_id: response.branch_id, 
                        imagePath: response.imagePath.replace("\\", "/"),
                        caption: response.caption, 
                        description: response.description, 
                        date: response.date,
                        absoluteImagePath: response.absoluteImagePath,
                        meta: {
                            type: "GET", 
                            url: "some.url",
                        }
                    }
                })
            })
        .catch((error) => {
            console.log(error);
            res.status(500).json({
                error: error
            })
        })
})

【问题讨论】:

标签: javascript node.js express multer


【解决方案1】:

不完全是作者的要求,但如果您希望使用 JWT 或类似的东西验证请求,您可以在请求标头中添加身份验证数据,例如

Authorization: TOKEN_OR_ANY_AUTHETICATION_DATA

您将能够访问标题而无需访问正文,因此它可能会解决您的问题。这样您就可以在中间件中使用这些数据。或您在上传文件之前调用的任何函数

【讨论】:

    【解决方案2】:

    我认为您可以在 multer 实际中间件之前使用中间件。像下面的代码:

    const validator = function(req, res, next) {
        // Do some validation and verification here
        if(okay)
           return next();
        else
           return res.status(400).send({message: 'Invalid Arguments(For Example!)'})
    }
    

    并在upload.single之前将此函数用作中间件,就像这样:

    router.post("/", validator, upload.single("gallery_item_image"), function (req, res, next) {
        // Your code goes here
    }
    

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-04
      • 2017-05-30
      • 2018-06-18
      • 2015-01-03
      • 2019-07-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多