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

时间:2015-12-02 03:48:38

标签: node.js express middleware multer

我正在使用快速路由器来定义我的路由,我需要添加一个中间件,所以有些路由,只需在回调函数之前添加中间件就会输出以下错误:

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
    }

})();

1 个答案:

答案 0 :(得分:1)

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

由于您计划上传多个文件,因此需要使用transaction_docs.array(fieldName[, maxCount]),这意味着它将接受一个文件数组,所有文件都使用名称fieldname。如果上传的maxCount文件超过maxCount,则可选择输入错误。文件数组将存储在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 
  // 
  // e.g. 
  //  req.files['avatar'][0] -> File 
  //  req.files['gallery'] -> Array 
  // 
  // req.body will contain the text fields, if there were any 
})