In one of the examples in the request's documents shows this example:
https://www.npmjs.com/package/request#custom-http-headers
var request = require('request');
var options = {
url: 'https://api.github.com/repos/request/request',
headers: {
'User-Agent': 'request'
}
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
var info = JSON.parse(body);
console.log(info.stargazers_count + " Stars");
console.log(info.forks_count + " Forks");
}
}
request(options, callback)
Lets' say I want the value of the variable info return to me.
How do I do it?
You cannot pass a value from an asynchronous command. The most common strategy used in Node.js is to wrap the code that requires the info variable in a function and call that from the callback.
eg:
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
functionThatUsesInfo(info);
}
}
Related
I try to get the JSON data from a GET request and I can see the information from body in request. How can I get the data?
Currently use NodeJs, basic in JavaScript.
var definedURL="https://api.etherscan.io/api?module=account&action=tokentx&contractaddress=0x6a750d255416483bec1a31ca7050c6dac4263b57&page=1&offset=100&sort=asc&apikey=YourApiKeyToken";
var request = require('request')
var information=[];
request({
url: definedURL,
json: true
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
//console.log(body.result[0]);
information.push(body.result[0]);
}
});
console.log(information);
I expect after this I will see the contain of result coming out, but now it still shows [].
Because you are making asynchronous request. Asynchronous action will get completed after the main thread execution.
console.log(information) // execute before your call
You need to wait for the request call to get completed and received data get pushed to information
There can be two ways to do this -
Async/Await- MDN Reference
var definedURL="https://api.etherscan.io/api?module=account&action=tokentx&contractaddress=0x6a750d255416483bec1a31ca7050c6dac4263b57&page=1&offset=100&sort=asc&apikey=YourApiKeyToken";
var request = require('request')
var information=[];
async () => {
await request({
url: definedURL,
json: true
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
//console.log(body.result[0]);
information.push(body.result[0]);
}
});
console.log(information)
}();
Promise MDN reference
var definedURL="https://api.etherscan.io/api?module=account&action=tokentx&contractaddress=0x6a750d255416483bec1a31ca7050c6dac4263b57&page=1&offset=100&sort=asc&apikey=YourApiKeyToken";
var request = require('request')
var information=[];
var Promise = new Promise((resolve,reject) => {
request({
url: definedURL,
json: true
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
//console.log(body.result[0]);
information.push(body.result[0]);
resolve()
}
});
})
Promise.then(() => {
console.log(information)
})
I'm using request npm module
var request = require('request');
request('http://www.google.com', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body) // Show the HTML for the Google homepage.
}
})
my response return format such as "string". How to convert response to object?
I found answer
request('http://www.google.com', function (error, response, body) {
if (!error && response.statusCode == 200) {
var info = JSON.parse(body);
console.log(info ) // Show the HTML for the Google homepage.
}
})
I am using the request package to make a simple HTTP GET request to the npm API. I am trying to get the download counts for npm packages from an arbitrary function in my nodeJS backend.
Here is my updateDownloadCount.ts file:
export function updateDownloads() {
plugin.find(function (err, plugins: Array<any>) {
for (let plugin of plugins) {
var url = 'https://api.npmjs.org/downloads/point/last-month/' + plugin.package;
request(url, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body)
}
})
}
})
}
So that's fine and I get a string of outputs like:
{"downloads":17627637,"start":"2016-08-29","end":"2016-09-27","package":"request"}
however, when I try to access just the downloads count, i.e.
console.log(body.downloads);
I get undefined console logged... How can I access the body variables? I feel like this should be super simple, but I couldn't find any docs on it.
Try to parse body if it is string type
export function updateDownloads() {
plugin.find(function(err, plugins: Array < any > ) {
for (let plugin of plugins) {
var url = 'https://api.npmjs.org/downloads/point/last-month/' + plugin.package;
request(url, function(error, response, body) {
if (!error && response.statusCode == 200) {
if (body && typeof body == "string") {
body = JSON.parse(body);
}
console.log(body.downloads);
}
})
}
})
}
Still learning node. Based upon the following:
https://github.com/request/request
var request = require('request');
request('http://www.google.com', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body) // Show the HTML for the Google homepage.
}
})
I wish to create the above as a reusable block of code so thought I'd wrap it in a function passing the URL as a parameter such as:
var request = require('request');
var URL;
var request = require('request');
request('http://www.google.com', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body) // Show the HTML for the Google homepage.
}
})
function fetchURL (URL) {
request(URL, function (error, response, body) {
if (!error && response.statusCode == 200) {
return body;
}
});
};
var a = fetchURL('http://www.google.com');
console.log(a);
This works however I am unsure of whether "return body" is needed as it also works without this line. Happy to received comments on my coding style too as it's all new to me.
The pattern in Node is to provide a callback as an argument to an asynchronous function. By convention, this callback function has error as its first argument. For example:
function fetchURL(url, callback) {
request(url, function(error, response, body) {
if (!error && response.statusCode == 200) {
callback(null, body);
} else {
callback(error);
}
});
};
fetchURL('http://www.google.com', function(err, body) {
console.log(body);
});
Note that in your snippet, return body; is a return from the anonymous callback function passed into fetchURL(). fetchURL() itself returns nothing.
I'm struggling with working out how to get the return data from this code example. If I try to get the cert data from the callback function its always empty. Is there something I'm missing here?
var Request = require('request');
function callhttp(host) {
var cert = " ";
var options = {
url: 'https://' + host
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
var cert = response.connection.getPeerCertificate();
}
}
Request(options, callback);
return cert
}
console.log(callhttp("www.google.com"));
Best Regards.
By returning 'cert' you refer to the operation as a sync one, which is not.
The correct pattern is to pass a callback function and handle the data whitin:
var Request = require('request');
function callhttp(host, cb) {
var cert = " ";
var options = {
url: 'https://' + host
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
var cert = response.connection.getPeerCertificate();
cb(cert);
}
}
Request(options, callback);
}
callhttp("www.google.com", function(_cert) {
console.log(_cert);
});