简体   繁体   中英

Axios POST to Mailchimp API: HTTP Authentication not working

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.

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=""

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM