javascript - Node 如何全局访问对象

标签 javascript node.js

我正在学习 Node js。因此,作为练习,我想使用 twit 与 twitter api 进行交互。 我使用 Twitter 登录,并在我的主文件 ( server.ts ) 上取回访问 token 和密码,我记录它,并获得正确的凭据。 然后我将它存储在本地(我读到的是在 Node 中创建全局变量的方法,这太疯狂了)然后,当我想在另一个路由文件中使用时,我得到错误:ReferenceError: Tobj is not defined

这是我实例化对象的方式:

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 对象呢?我以为我所要做的就是使用本地人。

最佳答案

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

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

关于javascript - Node 如何全局访问对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47119507/

相关文章:

javascript - 如何按值选择其值包含加字符的元素?

javascript - 必须使用事件访问 token 来查询有关具有开放图的当前用户的信息

node.js - 使用 AWS SDK 为事件桥规则添加 AWS Lambda 作为目标

javascript - Sencha 触摸 : How to get the simple json file as response using JSONP?

javascript - 类型错误 : Cannot read property 'go' of undefined

javascript - 在node.js中使用forEach引用JSON对象

javascript - 从 Meteor 中的另一个模板获取 react 变量

node.js - npm update 不做任何事情

node.js - 在 nodejs 中使用 wkhtmltopdf 将 html 转换为 pdf

javascript - 过滤器与过滤器