0

I'm banging my head for not learning from the basics and just jumping in.

I'm building an API that returns the SSL Certificate status of a domain. It's working fine on console.log but the JSON output is empty, obviously because the exports get executed before the https request ends.

How do I incorporate the exports in response.on(end) function? Thanks a lot!

function getSSL(domain) {

    var options = {
        host: 'www.'+domain+'.com',
        method: 'get',
        path: '/'
    };

    var isAuth = false;

    callback = function(response) {

        response.on('data', function () {
            isAuth = response.socket.authorized;
        });

        response.on('end', function () {
            console.log(isAuth);
        });

    }   
    
  var req = https.request(options, callback).end();
}

exports.findByDomain = function (req, response) {
    var id = req.params.id;
    sslCheck = getSSL(id);
    response.send(sslCheck);
};
Daniel H
  • 5
  • 5
  • `getSSL` needs a callback as the second param to return the data. It'll look like: `getSSL(id, function(data) { response.send(data) });` – tymeJV Jul 13 '15 at 15:02
  • [Related/dupe](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call), whereby `isAuth` is the thing you want to be passing to an ultimate callback function, probably defined within your `findByDomain` function. – James Thorpe Jul 13 '15 at 15:03

1 Answers1

2

Yes, the response.send(sslCheck); gets executed before getSSL(id); has a chance to finish. You need to send in a callback so it can be executed after getSSL(id); finishes:

function getSSL(domain, callback) {

    var options = {
        host: 'www.'+domain+'.com',
        method: 'get',
        path: '/'
    };

    var isAuth = false;

    var httpCallback = function(response) {

        response.on('data', function () {
            isAuth = response.socket.authorized;
        });

        response.on('end', function () {
            console.log(isAuth);
            callback(isAuth);
        });

    }

  var req = https.request(options, httpCallback).end();
}

exports.findByDomain = function (req, response) {
    var id = req.params.id;
    getSSL(id, function(sslCheck) {
        response.send(sslCheck);
    });
};
Sukima
  • 9,627
  • 3
  • 42
  • 58
  • Thanks a lot, worked fine! Now I just need to investigate a better way of retrieving SSL information without the overhead of the whole firstpage html. – Daniel H Jul 13 '15 at 15:15