Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js https.get() fires error ECONNREFUSED

One of the steps of the OAuth dance involves exchanging a code received via a callback for an access token. Specifically for Facebook server side auth, the following https GET request returns the access code in the response body:

https://graph.facebook.com/oauth/access_token?
  client_id=YOUR_APP_ID
  &redirect_uri=YOUR_REDIRECT_URI
  &client_secret=YOUR_APP_SECRET
  &code=CODE_GENERATED_BY_FACEBOOK

Node.js fires an error when attempting to connect thus:

 https.get( /**String | Object*/ options, function ( res ) {
   res.setEncoding( 'utf8' );

   res.on( 'data', function ( data ) {
     // parse response body
   } );

 } ).on( 'error',function ( e ) {
      Log.w( TAG, "Error requesting access_token", e );
 } ).end();

The error is:

{  code: 'ECONNREFUSED',
   errno: 'ECONNREFUSED',
   syscall: 'connect' }

The call works fine with wget/curl so its not a question of outgoing firewall rules or such. What is wrong with the node request?

like image 398
Venkat Peri Avatar asked Apr 10 '13 14:04

Venkat Peri


1 Answers

Turns out the issue was https certificate verification failure. From node's https.request() docs:

rejectUnauthorized: If true, the server certificate is verified against the list of supplied CAs. An 'error' event is emitted if verification fails. Verification happens at the connection level, before the HTTP request is sent. Default true.

Unless explicitly provided, http[s].[request|get] will use the global Agent which ignores tls.connect() options including the rejectUnauthorized flag. The call to get (or request) needs to be modified thus:

var options = require('url').parse( /**String*/ url );
options.rejectUnauthorized = false;
options.agent = new https.Agent( options );

https.get( /**Object*/ options, function ( res ) {
  // handle response & body
} ).on( 'error',function ( e ) {
  // handle errors
} ).end();
like image 123
Venkat Peri Avatar answered Sep 27 '22 22:09

Venkat Peri