Node Express - multer 导致控制器调用失败,反之亦然

Node Express - multer causing controller call failure and vice versa

Routes.js

下面的代码有效。

var upload= multer({ storage: storage})
app.post('/upload', [ upload.any(), function(req, res) {
     console.log(req.body) // form fields
     console.log(req.files) // form files
     res.status(204).end()
   }]);

但是,我也想调用位于我的文件中的控制器方法 uploadController.js

所以我在下面做了这个。

 app.post('/upload', controllers.uploadFiles.upload, [ upload.any(), function(req, res) {
                    console.log(req.body) // form fields
                    console.log(req.files) // form files
                    res.status(204).end()
                }]);

然而,发生的事情是我的控制器被调用但上传部分失败,即没有调用下面的部分。

console.log(req.body) // form fields
 console.log(req.files) // form files
 res.status(204).end()

总之,其中一个(multer 或控制器)可以工作,两个都不能。 这可能有什么问题?

更新

尝试了以下方法。只有控制器被调用。没有文件上传完成。

  app.post('/upload', controllers.dataUpload.upload, [ upload.any(), function(req, res, next) {
                    console.log(req.body) // form fields
                    console.log(req.files) // form files
                    next()
                }]);

您还没有从第一个控制器调用 next。调用 res.end() 后执行结束。如果你想继续执行到下一个路由匹配,你必须在第一个中间件上调用next()

您可以在指南中阅读更多关于路由和中间件的信息:https://expressjs.com/en/guide/routing.html

以下是一些可能相关的引述:

您需要调用next函数,以便调用下一个控制器:

More than one callback function can handle a route (make sure you specify the next object).

当您在 res 对象上调用方法时,执行将终止并忽略下一个控制器:

The methods on the response object (res) in the following table can send a response to the client, and terminate the request-response cycle. If none of these methods are called from a route handler, the client request will be left hanging.

感谢@squgeim 帮助我完成了概念部分。根据他的指导,我想通了这个问题。下面是工作代码。

Routes.js

var uploadStorage = multer({ storage: storage})
app.post('/upload', controllers.uploadController.uploadFile, [uploadStorage.any(), function(req, res, next) {
    console.log(req.body) // form fields
    console.log(req.files) // form files
    res.status(204).end()
}]);

uploadController.js

module.exports = {
    uploadFile: (req, res, next) => {

        //Do whatever you want over here.
        next()
    },
}

所以基本上,在 app.post 参数 #2 中,我调用控制器,做任何我想做的事,然后调用 next() 继续前进到正在调用的 app.post 参数 #3 multer 和上传文件。