【问题标题】:Express.js: How to pass req object to middleware w/o creating a new route w/ MulterExpress.js:如何在不使用 Multer 创建新路由的情况下将 req 对象传递给中间件
【发布时间】:2019-02-21 19:43:25
【问题描述】:

我是 Express.js 和 StackOverflow 的新手;如果这是一个重复的问题,我很抱歉。我检查了,但没有看到任何相关内容。

所以,我使用 Multer + Express 允许用户将名为 '${username}.{extension}' 的图像上传到服务器端 /uploads/ 文件夹。我不希望用户能够在服务器上保存多个图像(即没有“user1.jpg”和“user1.png”)。为此,我编写了以下中间件:

function deleteUserImage(req){
    const acceptedExtensions = ['.png', '.jpg', '.jpeg', '.tif', '.tiff', '.JPG', '.bmp'];
    acceptedExtensions.forEach(char => {
        if(fs.existsSync(`./uploads/${req.cookies.username+char}`)){
            fs.unlinkSync(`./uploads/${req.cookies.username+char}`);
        }
    })
}

然后我能够通过以下路线获得我想要的功能:

app.post('/process_upload-image', (req, res, next) => { //User sends post req w/ image file
    deleteUserImage(req) //images for that user are cleared.
    next();
})

app.post('/process_upload-image', upload.single('user-image'), (req, res, next) => {
    res.redirect('/welcome'); //user is redirected after multer uploads the image.
})

我想知道这是否是最佳实践,因为您最终会在同一个 URI 上监听两条路由?有没有办法将 req 传递给 deleteUserImage(),然后调用 upload.single()...all in one route?

谢谢!

【问题讨论】:

    标签: javascript node.js express multer


    【解决方案1】:

    您可以简单地在一条路由上链接多个中间件。将deleteUserImage 函数更改为:

    function deleteUserImage(req, res, next){
       const acceptedExtensions = ['.png', '.jpg', '.jpeg', '.tif', '.tiff', '.JPG', '.bmp'];
       acceptedExtensions.forEach(char => {
           if(fs.existsSync(`./uploads/${req.cookies.username+char}`)){
               fs.unlinkSync(`./uploads/${req.cookies.username+char}`);
           }
       })
    
       next()
    }
    

    然后删除第一个路由并将第二个更改为:

    app.post('/process_upload-image', deleteUserImage, upload.single('user-image'), (req, res, next) => {
        res.redirect('/welcome');
    })
    

    【讨论】:

    • 我认为一定有这样的东西。谢谢!!我已经对答案投了赞成票,但我没有足够的代表来显示它。
    猜你喜欢
    • 2015-09-28
    • 2023-03-10
    • 2020-07-25
    • 1970-01-01
    • 2019-05-31
    • 1970-01-01
    • 2012-04-14
    • 2021-09-10
    • 2022-12-17
    相关资源
    最近更新 更多