2014-12-29 30 views
2

我有一些中間件來檢查,如果用戶登錄:傳遞參數去定製中間件

//mw.js 
module.exports = { 
    auth: function(req, res, next) { 
    //check if user is logged in here 
    } 
} 

,我有一個接受用於撥打電話,以第三方服務client一個單獨的路由文件:

//routes.js 
module.exports = function(app,client) { 
    router.get('/', mw.auth, function (req, res) { 

    }); 
} 

正如您所看到的,該路由使用中間件,但我怎樣才能將client傳遞給中間件,以便它也可以使用第三方服務呢?

回答

3

的首選方法來傳遞參數/配置選項,以中間件是通過返回從捕捉使用閉包的參數中間件的功能。

//mw.js 
module.exports = { 
     auth: function (client) { 
     return function (req, res, next) { 
      //use client 
     }; 
     } 
    } 

...

//routes.js 
module.exports = function(app,client) { 
    router.get('/', mw.auth(client), function (req, res) { 

    }); 
} 

static file server middleware,爲例如,採用的基本目錄作爲參數。

以下是我執行json-rpc的摘錄。它捕獲方法對象並在請求到達時調用方法。

var JsonRpcServer = require('./rpc-server'); 

module.exports = function jsonrpc (methods) { 
    var jsonRpcServer = new JsonRpcServer(methods); 
    return function(req, res, next) { 
     var rpcResponse, 
     rpcRequest = req.body, 
     contentType = req.headers['content-type']; 

     if(req.method === 'POST' && ~contentType.indexOf('application/json')) { 
      rpcResponse = jsonRpcServer._handleRpc(rpcRequest); 
      if(Array.isArray(rpcResponse) && rpcResponse.length || rpcResponse.id) { 
       rpcResponse = JSON.stringify(rpcResponse); 
       res.writeHead(200, { 
        'Content-Length': String(Buffer.byteLength(rpcResponse)), 
        'Content-Type': contentType 
       }); 
       res.end(rpcResponse); 
      } 
      else { 
       res.end(); 
      } 
     } 
     else next(); 
    }; 
}; 
2

你可以將其連接到app

//routes.js 
module.exports = function(app,client) { 
    app.client = client; 
    router.get('/', mw.auth, function (req, res) { 

    }); 
} 

//mw.js 
module.exports = { 
    auth: function(req, res, next) { 
    //check if user is logged in here 
    // use `req.app.client` here 
    } 
}