使用Express.Router()快速路由特定的中间件

我使用express路由器来定义我的路由,我需要添加一个中间件,所以有些路由,只是在callback函数之前添加中间件输出以下错误:

Error: Route.post() requires callback functions but got a [object Object] 

我正在使用文件夹作为模块,我的模块上传,这里是index.js

 module.exports = (function () { var express = require( 'express' ), router = express.Router(), multer = require( 'multer' ), transaction_docs = multer( { dest: './client/public/docs/transactions/' } ), product_images = multer( { dest: './client/public/img/products' } ), upload = require( './upload' ); router.route( '/upload/transaction-docs' ) .post( transaction_docs, upload.post );//If I take off transaction_docs theres no error router.route( '/upload/product-images' ) .post( product_images, upload.post );//Same as above return router; })(); 

这里是upload.js

 module.exports = (function () { function post( request, response ) { var filesUploaded = 0; if ( Object.keys( request.files ).length === 0 ) { console.log( 'no files uploaded' ); } else { console.log( request.files ); var files = request.files.file1; if ( !util.isArray( request.files.file1 ) ) { files = [ request.files.file1 ]; } filesUploaded = files.length; } response.json( { message: 'Finished! Uploaded ' + filesUploaded + ' files.', uploads: filesUploaded } ); } return { post: post } })(); 

你正在使用不正确的方式。 对于中间件,您不能直接使用transaction_docs或product_images,因为它们不是函数。

由于您打算上传多个文件,因此您需要使用transaction_docs.array(fieldName[, maxCount]) ,这意味着它将接受一个文件数组,全部使用名称fieldname。 如果超过maxCountfile upload,可以select错误。 文件数组将被存储在req.files中。

例:

 var express = require('express') var multer = require('multer') var upload = multer({ dest: 'uploads/' }) var app = express() app.post('/profile', upload.single('avatar'), function (req, res, next) { // req.file is the `avatar` file // req.body will hold the text fields, if there were any }) app.post('/photos/upload', upload.array('photos', 12), function (req, res, next) { // req.files is array of `photos` files // req.body will contain the text fields, if there were any }) var cpUpload = upload.fields([{ name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }]) app.post('/cool-profile', cpUpload, function (req, res, next) { // req.files is an object (String -> Array) where fieldname is the key, and the value is array of files // // eg // req.files['avatar'][0] -> File // req.files['gallery'] -> Array // // req.body will contain the text fields, if there were any })