MrMilkShake
MrMilkShake

Reputation: 51

Nodejs post request variable scope issue

I'm somewhat new to Nodejs. In the following code I'm getting data from an API.

request.post({ url:endpoint, form: requestParams }, function (err, response, body) {
    if (err) {
        console.log("Error = " + err);
    }
    else {
        let parsedBody = JSON.parse(body);
        if (parsedBody.error_description) {
            console.log("Error = " + parsedBody.error_description);
        }
        else {
            // testFunc(AccessToken);
            test = "Success!";
            testFunc(test);
        }
    }
});

function testFunc(success){
    Token = success;
    console.log(Token);
}

// this code gives the error "Token is not defined" \/
console.log(Token);

in the post request i make the variable "test". I want to be able to use this as a global variable so i can use it in a get request.

When i console.log() "Token" in the "testFunc" it will log it correctly. But when i console.log() outside the function it gives the error Token is not defined.

How can i get the "Token" or the "test" variable to be global so i can use it in another get request?

Thanks in advance!

Upvotes: 1

Views: 261

Answers (2)

har17bar
har17bar

Reputation: 884

your request.post is running asynchronous you can use request-promise lib

const request = require("request-promise"); 

and change to

var result = await request(options);

or for more knowledge read this article https://blog.risingstack.com/mastering-async-await-in-nodejs/

Upvotes: 1

app_zone
app_zone

Reputation: 54

your Token is local variable on the testFunc

function testFunc(success){
    Token = success;
    console.log(Token);
}

try to define the Token as the global variable you can put after all import require(...) or above the request.post

let Token; //this is global declared variable

and also your console.log cannot be just like your code

as your question I want to be able to use this as a global variable so i can use it in a get request.

so you need to put your console.log inside the request.get

something like

request.get('xxxxxx', , function(err) {
    console.log("Token is " , Token);
});


Upvotes: 1

Related Questions