Node.js 将参数传递给自定义中间件

Node.js 将参数传递给自定义中间件,node.js,express,Node.js,Express,我有一些检查用户是否登录的中间件: //mw.js module.exports = { auth: function(req, res, next) { //check if user is logged in here } } 我有一个单独的路由文件,它接受一个用于呼叫第三方服务的客户端: //routes.js module.exports = function(app,client) { router.get('/', mw.auth, function (re

我有一些检查用户是否登录的中间件:

//mw.js
module.exports = {  
  auth: function(req, res, next) {
    //check if user is logged in here
  }
}
我有一个单独的路由文件,它接受一个用于呼叫第三方服务的
客户端

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

  });
}

如您所见,路由使用中间件,但如何将
客户端
传递给中间件,使其也可以使用第三方服务?

您可以将其连接到
应用程序

//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
  }
}

向中间件传递参数/配置选项的首选方法是从中间件返回一个函数,该函数使用闭包捕获参数

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

例如,将基目录作为参数

下面是我实现的一个摘录。它捕获methods对象,并在请求到达时调用该对象上的方法

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();
    };
};
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();
    };
};