PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, September 6, 2022

[FIXED] How to add API key to Axios post request for mailchimp

 September 06, 2022     api-authorization, axios, basic-authentication, mailchimp-api-v3.0     No comments   

Issue

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


Answered By - Phil
Answer Checked By - Marie Seifert (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

1,204,563

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © 2025 PHPFixing