想知道以下情况下共享变量的“好方法”。
我的server.js
文件包括这样的authenticator.js
文件:
var authenticator = require('./server/services/authenticator')(app);
app.use(authenticator);
在该authenticator.js
文件中,有一个叫做专用密钥变量:
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
文件?
您可以将其附加到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;
};
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句