Mike Perrenoud
Mike Perrenoud

Reputation: 67898

Socket hang up error on https request to external API?

I'm receiving a socket hang up error when attempting to access an external API. The external API can be reached manually (click here) and returns results even when using my API key (that's a development API key used to demonstrate the API on the site).

The code I'm using looks like the following. Please note when you see my_api_key the real key exists.

var zipCodeApiPath = '/rest/my_api_key/radius.json/{{zip}}/15/mile';
...
var https = require('https');
...
var options = {
    hostname: 'zipcodedistanceapi.redline13.com',
    port: 443,
    path: zipCodeApiPath.replace('{{zip}}', zipCode),
    method: 'GET',
    secureProtocol: 'SSLv3_method'
};
options.agent = new https.Agent(options);

console.log(options);

https.request(options, function(res) {
    console.log(res);
    ...
});

When logging out the options to the console I get this:

{ hostname: 'zipcodedistanceapi.redline13.com',
  port: 443,
  path: '/rest/my_api_key/radius.json/80549/15/mile',
  method: 'GET',
  secureProtocol: 'SSLv3_method',
  agent:
   { domain: null,
     _events: { free: [Function] },
     _maxListeners: 10,
     options: [Circular],
     requests: {},
     sockets: {},
     maxSockets: 5,
     createConnection: [Function: createConnection] } }

Why won't it respond?

Code in Progress

Below is the code in progress based off of the answer by mscdex.

var req = https.request(options, function(res) {
    var response = '';
    res.on('data', function(chunk) {
        response += chunk;
    });

    res.on('end', function() {
        var newObj = {
            zip: zipCode,
            codes: JSON.parse(response).zip_codes
        };

        coll.insert(newObj, function(err, item) {
            if (err) {
                callback(err);
            }
            else {
                console.log(item.codes);

                callback(null, item.codes);
            }
        });
    });
});
req.end();

req.on('error', function(e) {
    console.log(e);
});

Upvotes: 1

Views: 1737

Answers (1)

mscdex
mscdex

Reputation: 106698

There's a couple of things missing here:

  • You are not calling .end() on your request object so that the request can be sent to the server.

  • You should read from the response stream.

Upvotes: 1

Related Questions