Axios POST to Mailchimp API: HTTP Authentication not working
Asked Answered
S

1

8

I'm trying to make an axios request to my mailchimp account. But it does not seem to be working. I cannot get it to authorize me - what am I doing wrong here? I have been following this tutorial: which says:

There are 2 authentication methods for the API: HTTP Basic authentication and OAuth2. The easiest way to authenticate is using HTTP Basic authentication. Enter any string as your username and supply your API Key as the password. Your HTTP client library should have built-in support for Basic authentication, but here’s a quick example that shows how to authenticate with the --user option in curl:

curl --request GET \
--url 'https://<dc>.api.mailchimp.com/3.0/' \
--user 'anystring:<your_apikey>'

So I implemented:

axios.post('https://us1.api.mailchimp.com/3.0/lists/xad81287/members/', {
      auth:
        {
          url: 'https://us1.api.mailchimp.com/3.0',
          user: 'blabla:11231h23123j14bhj1b23j12-us1' //this is my API key
        },
      firstName: 'Fred',
      lastName: 'Flintstone'
    })
    .then(function (response) {
      console.log(response);
    })
    .catch(function (error) {
      console.log(error);
    });

(I have changed the API things and list names here randomly)

Error I'm getting:

OPTIONS https://us1.api.mailchimp.com/3.0/lists/afafaf/members/ 401 (Unauthorized) dispatchXhrRequest @ xhr.js:178 xhrAdapter @ xhr.js:12 dispatchRequest @ dispatchRequest.js:59 Promise resolved (async) request @ Axios.js:51 Axios.(anonymous function) @ Axios.js:71 https://us1.api.mailchimp.com/3.0/lists/afafaf/members/: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access. The response had HTTP status code 401.

Septemberseptembrist answered 14/2, 2018 at 15:29 Comment(3)
Were you able to fix this ?Rhodian
Any solution? I can make it work fine in terminal and postman, etc. can't get it working with axios......Savil
back end written in which language ?Gynoecium
T
-3

Try this:

axios({
  method:'post',
  url: 'https://us1.api.mailchimp.com/3.0/lists/xad81287/members/',
    auth: {
      username: 'Fred', // anystring
      password: '11231h23123j14bhj1b23j12-us1' // Your API key
    }
}).then(response => console.log(response)).catch(error => console.log(error))

It work for me.

For work with Mailchimp API from localhost (so that there is no CORS error) quit Google Crome and open it with this command:

open -a Google\ Chrome --args --disable-web-security --user-data-dir=""
Torquemada answered 24/1, 2019 at 12:8 Comment(2)
I am at a complete loss as to why you think that would solve the cross-origin permissions problem.Arytenoid
Because today I was faced with this problem and this decision was the right one.Torquemada

© 2022 - 2024 — McMap. All rights reserved.