1

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!

0

2 Answers 2

1

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/

Sign up to request clarification or add additional context in comments.

Comments

1

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


2 Comments

Making the variable global didn't work for me. I added the let Token; above the request.post but the console.log(Token) returns a undefined. The reason i didn't put the console.log() in the request.get already is just to test, since i can't access the variable outside the request.post i figured that i also can't access it inside the request.get
your request.post is running asynchronous. it mean even the Token is not assigned with value, your console.log at the below is already executed, thats why you get undefined

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.