跨多个文件共享变量

时间:2014-12-27 13:32:26

标签: node.js express

想知道以下方案共享变量的“好方法”。

我的server.js文件包含authenticator.js文件,如下所示:

var authenticator = require('./server/services/authenticator')(app);
app.use(authenticator);

authenticator.js文件中有一个名为privateKey的变量:

module.exports = function (app) {
  var authenticator = function (req, res, next) {
    //do some stuff here

    var privateKey = 'value from Basic Auth header'

  };
  return authenticator;
};

我的api.js文件现在需要此privateKey变量。

我以相同的方式添加api.js server.js文件:

var api = require('./server/api')(app);
app.use('/v1', api);

我也想通过privateKey使用类似的东西:

var api = require('./server/api')(app, privateKey);

问题:如何在privateKey文件中提供server.js,以便将其传递到api.js文件?

1 个答案:

答案 0 :(得分:0)

您可以将其附加到req变量

module.exports = function(app) {
    var authenticator = function(req, res, next) {
        //do some stuff here
        req.privateKey = 'value from Basic Auth header'; //This can be shared accross middlewares.
        next(); //don't forget to call this.
    };
    return authenticator;
};

server.js


var api = require('./server/api')(app);
app.use('/v1', api);

api.js


module.exports = function(api) {
    var api = function(req, res, next) {
        var privateKey = req.privateKey; //this is how we can use it
        //do something with it
        next();
    };
    return api;
};

}