节点如何全局访问对象

时间:2017-11-05 08:13:14

标签: javascript node.js

我正在学习节点js。所以我想用twit与twitter api进行交互。 我使用twitter登录,并在我的主文件(server.ts)上获取访问令牌和密码,我记录它,并获得正确的凭据。 然后我将它存储在本地(我读取的是在节点中创建全局变量的方式,这很疯狂)然后,当我想在另一个路径文件中使用时,我得到错误: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);
}));

然后在我的用户路由文件中我尝试记录它:

//profile route
router.get('/profile', (req,res,next) => {
    console.log('profile: ',Tobj);
    res.send('profile page')
});

所以,我得到了错误。那么如何在特定范围之外使用twitter对象呢?我认为我所要做的就是利用当地人。

2 个答案:

答案 0 :(得分:1)

您可以通过locals访问req,例如:

router.get('/profile', (req,res,next) => {
    console.log('profile: ', req.app.locals.Tobj);
    ...
});

答案 1 :(得分:0)

在另一个文件中创建一个单独的模块,您可以在其中获取或设置twitter配置。然后使用它

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

因此,用于存储配置以供以后使用的简单模块。好处是您可以更轻松地对您的设计进行单元测试。

相关问题