getting data from callbacks using node "request" library - node.js

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

Related

Node Js get data from URL and pass to new variable

I have created one NODE JS URL request to get JSON and pass it to the new variable var1.
Var1 can get data within request function when call var1 outside of request it returns null value why? how to get data from URL request and pass it to a new variable outside the Request URL?
function datadata() {
var var1 = 0;
var request = require('request');
request('http://x.x.x.x/json', function (error, response, body) {
if (!error && response.statusCode == 200) {
var importedJSON = JSON.parse(body);
var1 = importedJSON.result.data;
// show value of var1
console.log(var1);
}
});
// cannot show value of var1
console.log(var1);
return var1;
}
function datadata(){
var var1 = 0;
var request = require('request');
return new Promise(function(resolve, reject){
request('http://x.x.x.x/json', function (error, response, body) {
if (err) return reject(err);
try {
if (!error && response.statusCode == 200) {
var importedJSON = JSON.parse(body);
var1 = importedJSON.result.data;
console.log(var1);
} catch(e) {
reject(e);
}
});
});
}
datadata().then(function(res) {
console.log(res);
}).catch(function(err) {
console.err(err);
});
you can't get something outside the request that easy anyway you can try to use Promise
Example
const request = require('request');
var p = new Promise((resolve, reject) => {
request('http://x.x.x.x/json', function (error, response, body) {
if (!error && response.statusCode == 200) {
var importedJSON = JSON.parse(body);
resolve(importedJSON.result.data)
}
});
p.then((data) => {
console.log(data);
})
You can use a callback to the datadata like so
Check whether the body is found on the response, in that case change your code to
request('http://x.x.x.x/json', function (error,response) {
and
var importedJSON = JSON.parse(response.body);
You should do this because your importedJSON may not be having data because according to your code it's data comes from (body)
Mostly likely the json data will be found on the response.body.
Then we callback the specific data you want, in your case it's result.data. Again make sure the result.data can be found on the raw json data that the request gives you otherwise it won't output anything because there's nothing to output, most likely you will get errors
function datadata() {
var var1 = 0;
var request = require('request');
request('http://x.x.x.x/json', function (error,body,response) {
if (error && response.statusCode == 200) {
callback("There was an error")
}else{
var importedJSON = JSON.parse(body);
callback(importedJSON.result.data);
// show value of var1
console.log(var1);
});
}
datadata((error, var1) => {
if(error){
return console.log(error)
}
console.log(var1
})

How to call rest api in express js

I am new in nodejs and I am using express js, I am calling REST API and want to show the response, but my problem is that the response is showing in console.log but I want to pass the body(response) in assistant.ask, where I am wrong here is my code:
var request = require('request');
let rawInput = function (assistant) {
let rawInput = assistant.getRawInput();
request.post(
'http://xxxxxxx.ngrok.io/api/v1/240/respond',
{ json: { query: rawInput } },
function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
assistant.ask(body);
}
else{
console.log(error);
}
}
);

Return array from Node.js function

I'd like to read some information from an remote CSV file using a callback function. Not sure, how exactly to do this.
function:
function getRoomsFromCSV(allRoomsArray) {
var request = require('request');
request('http://localhost:3333/rooms.csv', function (error, response, body) {
if (!error && response.statusCode == 200) {
...
allRoomsText = allRoomsText.substr(0,allRoomsText.length-1) + ']}';
var allRoomsArray = JSON.parse(allRoomsText);
}
})
}
I'd like to call the function and loop through the result array.
var rooms = [];
getRoomsFromCSV( function (rooms) {
for(var i = 0; i < rooms.length; i++) {
console.log("i:",i);
}
However, the for loop is never called and the result (room) seems to be empty.
Try like this
function getRoomsFromCSV(allRoomsArray) {
var request = require('request');
request('http://localhost:3333/rooms.csv', function (error, response, body) {
if (!error && response.statusCode == 200) {
...
allRoomsText = allRoomsText.substr(0,allRoomsText.length-1) + ']}';
allRoomsArray(JSON.parse(allRoomsText)); //response params to callback
}
})
}
You sent callback to retrieve response. so call that callback inside the async function

npm request module--return a value

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

Change variable value within async function - node.js

var url = posts.paging.next;
for (var i = 0; i < 3; i++) {
(function(url,i) {
request(url,{json:true}, function (error, response, body) {
if (!error && response.statusCode == 200) {
url = body.paging.next;
console.log(i+"+++"+url)
}
});
})(url,i);
};//for
According to async request response (body.paging.next), İ want to change value of var url which is top of code .Please Help
NOTE: i'm trying to get all comments from facebook api , To do that , i need to get page links . Because of this , i wrote this codes , if you have any other alternative way please suggest them thanx
Assuming that you're trying to perform the requests in sequence (e.g. the next request relies on the url from the previous request), you could do something like (using the async module):
var async = require('async');
// ...
var url = posts.paging.next, i = 0;
async.whilst(
function() { return i < 3; },
function(callback) {
++i;
request(url, { json: true }, function(err, response, body) {
// TODO: handle `err`
//return callback(err);
if (!err && response.statusCode === 200) {
url = body.paging.next;
console.log(i + '+++' + url);
callback();
}
});
},
function(err) {
// done!
}
);

Resources