10000RubyPools 10000RubyPools - 2 months ago 26
Javascript Question

Node.js HTTP Get Request to Mailchimp Returns Error

Whenever I run the following curl code, my request to the Mailchimp 3.0 API goes through just fine:

curl --request GET \
--url 'https://us12.api.mailchimp.com/3.0/' \
--user 'anystring:APIKEY'


However, whenever I make a request to the API using Node.js, I receive the following error:

Got error: connect ECONNREFUSED 127.0.0.1:80


I'm assuming I'm missing something or have something mismatched within my .js file, any ideas as to what that might be? Node code is below:

"use strict";
/* globals require, console */
var http = require('http');


var options = {
url: 'https://us12.api.mailchimp.com/3.0/',
headers: {
'Authorization': 'anystring:APIKEY',
'Content-Type': 'application/json',
}
};

http.get(options, (res) => {
console.log(`Got response: ${res.statusCode}`);
// consume response body
res.resume();
}).on('error', (e) => {
console.log(`Got error: ${e.message}`);
});


EDIT: Using uncaught exception returns the following:

Error: connect ECONNREFUSED 127.0.0.1:80
at Object.exports._errnoException (util.js:856:11)
at exports._exceptionWithHostPort (util.js:879:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1053:14)


EDIT 2: Fixed part of it. Was using
url
as one of my options instead of
host
. Here is the correct code for that portion:

var options = {
host: 'https://us12.api.mailchimp.com/3.0/',
headers: {
'Authorization': 'anystring:APIKEY',
'Content-Type': 'application/json',
}
};


Now I'm receiving the traceback
Got response: 400
instead of the data I'm looking to pull.

Answer

Alright I seem to have it working, a few things needed to be changed:

  1. As @I-Am-Not-Legend mentioned, the host and path options both needed to be set correctly.
  2. The anystring string needed to be changed to apikey

Once I did these two things, the request worked as expected. Full code is below, just make sure to switch out APIKEY with your actual API key, and switch out us12 with your account's corresponding datacenter (found at the end of your API key).

"use strict";
/* globals require, console */
var http = require('http');


var options = {
    host: 'us12.api.mailchimp.com',
    path: '/3.0/',
    headers: {
        'Authorization': 'apikey APIKEY',
        'Content-Type': 'application/json',
    }
};

http.get(options, (res) => {
  console.log(`Got response: ${res.statusCode}`);
  res.on('data', (chunk) => {
    console.log(`BODY: ${chunk}`);
  });
  // consume response body
  res.resume();
}).on('uncaughtException', function (err) { console.log(err); });
Comments