Express:为app.use抽象出中间件

时间:2015-12-29 11:22:02

标签: javascript node.js express middleware

我想在index.js中使用此代码

app.use(require('sass-middleware').middleware({
  src: path.resolve(__dirname, '../'),
  dest: path.resolve(__dirname, '../public')
}));
app.use(require('browserify-dev-middleware')({
  src: path.resolve(__dirname, '../'),
  transforms: [require('jadeify')]
}));

到此:

app.use(require('asset-pipeline-dev-middelware'));

但我只是不知道如何使传递给app.use的函数成为其他两个中间件函数的代理。

这样的东西填错了,还是没事?

require('asset-pipeline-dev-middelware')(app);

2 个答案:

答案 0 :(得分:2)

您可以像这样对中间件进行分组:

//asset-pipeline-dev-middelware.js
var middleware1 = require('first-middleware')
var middleware2 = require('second-middleware')

function(req, res, next){
    middleware1(req, res, function(err){
        if(err) return next(err);
        middleware2(req, res, next)
    })
}

然后就像你提到的那样在app中使用它:

app.use(require('asset-pipeline-dev-middelware'));

答案 1 :(得分:2)

这也有效,因为app.use可以处理数组

// asset-pipeline-dev-middelware.js
var middleware1 = require('first-middleware')
var middleware2 = require('second-middleware')

module.export = [middleware1, middleware2];

// index.js
app.use(require('asset-pipeline-dev-middelware'));