节点如何全局访问对象
我正在学习节点js。 所以作为一个练习,我想用twit与twitter api进行交互。 我用twitterlogin,并取回访问令牌和秘密,在我的主要文件(server.ts),我login,并获得正确的凭据。 然后我把它存储在本地(我读的是使节点,这是疯狂的全局variables的方式),然后,当我想在另一个path文件中使用我得到的错误:ReferenceError:Tobj未定义
这是我如何实例化对象:
passport.use(new Strategy({ consumerKey: 'myconsumerkey', consumerSecret: 'myconsumersecret', callbackURL: 'http://localhost:4000/twitter/return' },(token,tokenSecret,profile,callback) => { twitterconfig.access_token = token; twitterconfig.access_token_secret = tokenSecret; app.locals.Tobj = new Twit(twitterconfig); return callback(null,profile); }));
然后在我的用户路由文件我尝试logging它:
//profile route router.get('/profile', (req,res,next) => { console.log('profile: ',Tobj); res.send('profile page') });
所以,我得到的错误。 那么我怎样才能使用特定范围之外的Twitter对象呢? 我以为我所要做的就是使用当地人。
你可以通过req
访问locals
,比如:
router.get('/profile', (req,res,next) => { console.log('profile: ', req.app.locals.Tobj); ... });
在另一个文件中创build一个单独的模块,您可以在其中获取或设置Twitterconfiguration。 然后使用它
在twitterconfig.js(例如)
var twitconfig = null; module.exports.setConfig = function(config) { twitconfig = config; }; module.exports.getConfig = function() { return twitconfig; };
然后,当你想从另一个模块中设置或获取它时,需要twitterconfig.js。
var myconfig = require('./twitterconfig.js'); console.log(”config: ” + myconfig.getConfig());
所以,用于存储configuration的简单模块供以后使用。 好处是你可以更容易地unit testing你的devise。