skip to Main Content

i am learning node js. so as an exercise i want to use twit to interact with the twitter api.
i login with twitter, and get back the access token and secret, on my main file ( server.ts ), i log it, and get the right credentials.
then i store it in locals ( which i read is the way to make global variables in node, which is crazy) and then, when i want to use in in another route file i get the error: ReferenceError: Tobj is not defined

this is how i instantiate the object:

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);
}));

then in my user routes file i try to log it:

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

and so, i get the error. so how can i use the twitter object outside of that specific scope? i thought all i have to do is use the locals.

2

Answers


  1. Create a separate module in another file where you can get or set the twitter config. Then use it

    In twitterconfig.js (for example)

    var twitconfig = null;
    
    module.exports.setConfig = function(config) {
        twitconfig = config;
    };
    
    module.exports.getConfig = function() {
        return twitconfig;
    };
    

    Then when you keed to set or get it from another module, require twitterconfig.js.

    var myconfig = require(’./twitterconfig.js’);
    
    console.log(”config: ” + myconfig.getConfig());    
    

    So, simple module for storing the config for later use. The benefit is that you can more easily also unit test your design.

    Login or Signup to reply.
  2. You can access the locals through the req, such as:

    router.get('/profile', (req,res,next) => {
        console.log('profile: ', req.app.locals.Tobj);
        ...
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search