Reputation: 63
var request = require('request');
request("http://example.com/index.php?username=username&password=password, function (error, response, body) {
var n1 = body.search('<user>');
var n2 = body.search('</user>');
var final = body.slice(n1+6, n2);
//it is working perfectly here.
final10 = final;
});
//The problem is that i can not call the "body" or variable "Final10" outside the Scope.
var final10=request.body
Hi, I am Newbie in Node JS. I am trying to make a Experimental Bot. i am using "request" to send a "Get" to my website. there through "Php", it is getting saved in "Mysqli" database.
Everything is working fine and i am getting the result. but, as i had got the data required, i can not access it. How can i get access to the 'body' of 'Request' from outside the function?
Please refer above to the code
Is there any way, to call it outside of it? that i can manage my code more easily
Please Note: it is just a little snap of the code the real code. the real code got a lot of if/else, loops and other functions. Turing it into bracket under brackets will be little complicated.
Thankyou
Upvotes: 1
Views: 1091
Reputation: 71
So the request function is asynchronous, which means that you call request("http://...")
and node js fires that function, and then skips to the next line without waiting for it to finish. So if you had:
request("http://example.com/index.php?username=username&password=password", function() {
console.log("1");
});
console.log("2");
You would see 2
logged before 1
. Which brings us to the function that is the second argument of request: the callback function. You are passing in a function for request to call, once it has finished making the api request to your url. So if we change the above example to:
request("http://example.com/index.php?username=username&password=password", function() {
console.log("1");
console.log("2");
});
You would see 1
logged before 2
.
Request takes the function you pass in and injects the parameters: error, response and body which you can work with inside the callback function.
Because you are working with request through a callback function here, which gets called asynchronously, you can only use body
within the callback function.
request("http://example.com/index.php?username=username&password=password", function(error, response, body) {
// do something with the response body
console.log("Logging the response body", body);
});
You need to access the body within the scope of the callback function.
Upvotes: 1