Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js Https request Error

Tags:

node.js

https

I've tried the sample from the documentation and it works great.

But when I change the URL to https://api.mercadolibre.com/sites/, the request hangs. The only thing I get is:

{ [Error: socket hang up] code: 'ECONNRESET' }

Here's my code:

var https = require('https');

this.dispatch = function(req, res) {
  var renderHtml = function(content) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end(content, 'utf-8');
  }

  var parts = req.url.split('/');

  var options = {
    host: 'api.mercadolibre.com',
    port: 443,
    path: '/sites/',
    method: 'GET'
  };

  var request = https.request(options, function(res) {
    console.log("statusCode: ", res.statusCode);
    console.log("headers: ", res.headers);

    res.on('data', function(d) {
      process.stdout.write(d);
    });
  });

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

  request.end();
  return 'item id:' + parts[2];
};

I've tried with curl, soapui and with a browser. On all cases works great, but with node.js it doesn't.

How can I get more data on what's going on?

added

With curl i do: curl --sslv3 https://api.mercadolibre.com/sites/ works. I've test same in centos 6 and works too. I've reinstalled node, this time from source, same problem. My Os is ubuntu 12.04. Thanks.

like image 980
Norton Prot Avatar asked May 27 '12 05:05

Norton Prot


2 Answers

I'm not sure about api.mercadolibre.com site, but I can call API if I remove port param, like following code:

var options = {
    host: 'api.mercadolibre.com',
    path: '/sites/',
    method: 'GET'
};

And we also need add param to support SSL version 3:

https.globalAgent.options.secureProtocol = 'SSLv3_method';
like image 171
KimKha Avatar answered Oct 01 '22 14:10

KimKha


Why not use a library like request to deal with the details for you?

var request = require('request');

request('https://api.mercadolibre.com/sites/', {}, function(err, res, body) {
  console.log("Got body: ", body);
});

This yields:

Got body:  [{"id":"MLA","name":"Argentina"},{"id":"MLB","name":"Brasil"},{"id":"MCO","name":"Colombia"},{"id":"MCR","name":"Costa Rica"},{"id":"MEC","name":"Ecuador"},{"id":"MLC","name":"Chile"},{"id":"MLM","name":"Mexico"},{"id":"MLU","name":"Uruguay"},{"id":"MLV","name":"Venezuela"},{"id":"MPA","name":"Panamá"},{"id":"MPE","name":"Perú"},{"id":"MPT","name":"Portugal"},{"id":"MRD","name":"Dominicana"}]
like image 38
Asherah Avatar answered Oct 01 '22 15:10

Asherah