0

I'm using Node JS with Express. I have a callback Post which takes in the username and password from the user, generates a token from within another callback. My problem is accessing this token globally (across the application)

app.post('/custom', function (req, res, next) {
    //Get Username, password using body parser
    authService1.getToken({
        url: config.url
    }, function (err, token) {
        if (err) {
            next(err); //handling error
        } else {
            setToken(token);
            res.send(token);
            //token is accessible here 
        }
    });
});

function setToken(token) {
    global.t = token;
}

I have seen this question. I know AJAX is asynchronous. I'm trying to access the variable t in other JS files. There is no "use strict" pragma used on any of the JS files, so usage or declaration of a global variable isn't a problem (I guess). I'm OK with the design/maintenance issues that arise by using a global variable, so exports/locals is not a solution for me. Also, I want to be able to access this variable from outside callback functions (without using req/sessions variables)

What am I missing here? (I can access the token from within the else part)

Community
  • 1
  • 1
  • What happened if another user uses the function? Token overwrite? Why you should use as a global? Can put some code of where are used? – jesusgn90 Jan 27 '17 at 14:58
  • `What am I missing here?` the fact that without something to handle asynchrony your other files won't ever know wether the value is already available, or still pending, even if they could access it. Solution: create a promise, export it, and resolve it when the value is available. Or, to address the point that jesusgn90 mentioned, export a function that returns a promise resolving to the token. – Thomas Jan 27 '17 at 15:00
  • @jesusgn90 If it solves the core problem at hand : accessing that token in other JS files; I'm cool with that. Its an internal application and hence not going to production and used by a lot of users at the same time. – jagannathanr Jan 27 '17 at 15:05
  • @Thomas This is the solution that worked, please add it as an an answer. – jagannathanr Mar 09 '18 at 17:05

0 Answers0