I'm a bit of a newbie to NodeJS, but I've looked around all over and can't seem to find a solution to my problem below. I'm sure it's something simple, but thanks in advance for all help you can give me!
I'm trying to make a simple JSON scraper via NodeJS. All I need is for JSON to be stored to a variable. The problem is, I'm using Require, and their example just logs it to console. I've tried adding a variable after it's logging to the console, but I'm just getting undefined. Here's my code below, it's pretty simplistic so far :)
// var jsonVariable; Doesn't work, shown as a test
function getJSON(url){
var request = require("request")
request({
url: url,
json: true
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
console.log(body) // Print the json response
//return body; This doesn't work, nor does making a global variable called json and assigning it here. Any ideas?
//jsonVariable = body; // This also doesn't work, returning undefined even after I've called the function with valid JSON
}
})
}
Once again, thanks so much for any help you can give me :)
The problem is that the request
method is asynchronous, but you're trying to synchronously return a result. You'll need to either make a synchronous request (which doesn't appear to be possible with the request
package you're using), or else pass a callback function to be called when the request responds successfully. eg:
var request = require("request")
function getJSON(url, callback) {
request({
url: url,
json: true
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
callback(body);
}
});
}
getJSON('http://example.com/foo.json', function (body) {
console.log('we have the body!', body);
});
If you use 'return body' where does it return to? That function is being called as a parameter to the request() function. You also cannot define a variable in your anonymous function because you will not have access to it outside of that scope.
What you need to do is define a variable outside of function getJSON()
and then save body to that.
eg,
var result;
function getJSON(url){
var request = require("request")
request({
url: url,
json: true
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
result = body;
}
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.