RobDeFlop
RobDeFlop

Reputation: 59

NodeJS - Return a JSON from a request

I am currently doing some stuffs in NodeJS and now I have the following issue: When I get a JSON Object from a HTTP Request and want to return it, it's showing "undefined".

Here is my not working NodeJS Code:

 function verifyUser(uname,pword){
    var options = {
        url: 'CENSORED',
        method: 'POST',
        headers: headers,
        form: {'Username':uname, 'Password':pword, 'Key':key}
    }
    request(options,function(error,response,body){
        if(!error && response.statusCode == 200){
            return body;
        }
    })    
}

var test1 = verifyUser("RobDeFlop","CENSORED");
console.log(test1);

But when I replace the return with a console.log its showing me the json object. I hope someone can help me :)

Upvotes: 0

Views: 1165

Answers (1)

acenturyandabit
acenturyandabit

Reputation: 1418

Ah, the joys of learning async js in node for the first time :3

As @Mark_M mentioned, your function in request is only called after the request is processed. As a result, you can't return a variable from your verifyUser() function. verifyUser() returns immediately once it has SENT the request, and calls the funciton in request() once it has received an answer.

Ideally, you should follow the async flow by providing a callback function:

//We'll define some function called 'callback'
function verifyUser(uname,pword, callback){
    var options = {
        url: 'CENSORED',
        method: 'POST',
        headers: headers,
        form: {'Username':uname, 'Password':pword, 'Key':key}
    }
    request(options,callback);
    // Here I've changed your inline callback function to the one passed to verifyUser as an argument. 
}


// Then, your main code:
verifyuser("RobDeFlop","CENSORED", next);
function next(error,response,body){
        if(!error && response.statusCode == 200){
            //Do useful stuff with the body here.
        }
    })    
}

Upvotes: 1

Related Questions