Search code examples
javascriptnode.jsexpressmailchimp-api-v3.0

MailChimp Error Status: 401 Title: "API Key Invalid"


I am following a MailChimp API tutorial

When I test the API, I get a 401 response saying my API key is invalid.

Error - Status: 401

"Your API key may be invalid, or you've attempted to access the wrong datacenter."

I have yet to register a domain yet, this is being testing using a local server. Could this be error be caused by MailChimp's refusing the request for another reason, perhaps CORS?

app.post('/signup', (req, res) => {
  // Get form data
  const { email } = req.body;

  // Make sure field is filled
  if(!email) {
    res.redirect('/html/fail.html');
    return;
  }

  // Construct req data
  const data = {
    members: [
      {
        email_address: email,
        status: 'subscribed'
      }
    ]
  }
  // Convert to JSON
  const postData = JSON.stringify(data);

  const options = {
    url: 'https://us19.api.mailchimp.com/3.0/lists/listID',
    method: 'POST',
    headers: {
      Authorization: 'auth xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-us19'
    },
    body: postData
  };

  request(options, (err, response, body) => {
    if(err) {
      console.log(err);
      res.redirect('/html/fail.html');
    } else {
      if(response.statusCode === 200) {
        res.redirect('/html/success.html');
      } else {
        console.log(response.body);
        res.redirect('/html/fail.html');
      }
    }
  });
})


Solution

  • I tried running the same code in request in PostMan and I got back a 200 response.

    I was initially importing the API key from a config file, that I had not destructured...