Search code examples
axiosbasic-authenticationmailchimp-api-v3.0api-authorization

How to add API key to Axios post request for mailchimp


I'm trying to set up an axios post request to add members to an audience list, but I can't figure out how to add the API key (keeps giving error 401: 'Your request did not include an API key.'). I've tried a bunch of things in the "Authorization" header, like what I put below (also: "Bearer ${mailchimpKey}", "${mailchimpKey}", "Bearer ${mailchimpKey}", "Basic ${mailchimpKey}", and probably more...).

I also don't know what the "username" would be, but "any" worked when I tested the API elsewhere.

Does anyone know how I should set this up?

axios
.post(
  `https://${server}.api.mailchimp.com/3.0/lists/${list_id}/members`,
  {
    email_address: email,
    status: "subscribed",
  },
  {
    "User-Agent": "Request-Promise",
    Connection: "keep-alive",
    Authorization: `Basic any:${mailchimpKey}`,
    // Testing on localhost
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Headers": "Content-Type",
  }
)

Solution

  • If your intention is to use HTTP Basic authentication, just use the Axios auth config option

    axios.post(
      `https://${server}.api.mailchimp.com/3.0/lists/${encodeURIComponent(list_id)}/members`,
      {
        email_address: email,
        status: "subscribed",
      },
      {
        auth: {
          username: "anystring",
          password: mailchimpKey
        },
        headers: { // personally, I wouldn't add any extra headers
          "User-agent": "Request-Promise"
        }
      }
    )
    

    HTTP Basic auth headers look like

    Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=
    

    where the string after "Basic" is the Base64 encoded "username:password" string. Axios provides the auth option as a convenience so you don't need to encode the string yourself.

    Some other problems you had were:

    • Adding request headers outside the headers config option
    • Attempting to send Access-Control-Allow-Origin and Access-Control-Allow-Headers as request headers. These are response headers only. Adding them to your request will most likely cause more CORS errors