0

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.

1 Answer 1

2

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);
});
Sign up to request clarification or add additional context in comments.

2 Comments

Wow - OK. Thanks very much for this. It now works properly. Just out of interest what do the _ mean?
Nothing, just semantics for you to display the difference with the one inside the callhttp function

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.