thehappycactus thehappycactus - 5 months ago 102
Node.js Question

Mailchimp API v3.0 add email to list via NodeJS http

I'm using NodeJS to call the new MailChimp 3.0 API in order to add an email to a list. While I can get it working via POSTman, I'm having a hard time with Node's http:

var http = require('http');

var subscriber = JSON.stringify({
"email_address": "test@test.com",
"status": "subscribed",
"merge_fields": {
"FNAME": "Tester",
"LNAME": "Testerson"
}
});

var options = {
host: 'https://us11.api.mailchimp.com',
path: '/3.0/lists/<myListID>/members',
method: 'POST',
headers: {
'Authorization': 'randomUser myApiKey',
'Content-Type': 'application/json',
'Content-Length': subscriber.length
}
}

var hreq = http.request(options, function (hres) {
console.log('STATUS CODE: ' + hres.statusCode);
console.log('HEADERS: ' + JSON.stringify(hres.headers));
hres.setEncoding('utf8');

hres.on('data', function (chunk) {
console.log('\n\n===========CHUNK===============')
console.log(chunk);
res.send(chunk);
});

hres.on('end', function(res) {
console.log('\n\n=========RESPONSE END===============');
});

hres.on('error', function (e) {
console.log('ERROR: ' + e.message);
});
});

hreq.write(subscriber);
hreq.end();


Rather than getting even some sort of JSON error from Mailchimp, however, I'm getting HTML:

400 Bad Request

400 Bad Request



nginx



Is it clear at all what I"m doing wrong here? It seems pretty simple, yet nothing I've tried seems to work.

A few additional thoughts:


  1. While http's options have an "auth" property, I'm using the headers instead to ensure the authorization is sent without the encoding (as mentioned here). Still, I've also tried with the "auth" property, and I get the same result.

  2. I'm actually making this call from inside an ExpressJS API (my client calls the Express API, that calls the above code - I've edited all that out of this example for simplicity). That's why my variables are "hres" and "hreq", to distinguish them from the "res" and "req" in Express. Is there any reason that could be the issue?

  3. As mentioned above, I am able to get successful results when using POSTman, so I at least know my host, path, list ID, and API key are correct.


Answer

It turns out this had a very simple solution: the "host" property of the options object needed to have only the domain name. IE, remove the "https://" protocol:

var options = {
    host: 'us11.api.mailchimp.com',
    path: '/3.0/lists/<myListID>/members',
    method: 'POST',
    headers: {
        'Authorization': 'randomUser myApiKey',
        'Content-Type': 'application/json',
        'Content-Length': subscriber.length
    }
}