how do I make a post and get request with ReactJS, Axios and Mailchimp?

Viewed 5594

I am new to ReactJS and I am trying to build this app that need to use mailchimp so the user can subscribe for newsletter. I need to make a request using axios? can someone guide me through this? where do i put my api key? Did I do it correct in the bellow code? i put my mailchimps username in 'username' and my apikey in 'xxxxxxxxxxxxxxxxxxx-us16', however, i got the 401 error saying Unauthorized, BUT my console did say Fetch Complete: POST and caught no error.

import React, {Component} from 'react';
import './Subscribe.css';

class Subscribe extends Component {
  sub = () => {
    let authenticationString = btoa('username:xxxxxxxxxxxxxxxxxxx-us16');
    authenticationString = "Basic " + authenticationString;

    fetch('https://us16.api.mailchimp.com/3.0/lists/xxxxxxxxx/members', {
      mode: 'no-cors',
      method: 'POST',
      headers: {
        'Authorization': authenticationString,
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        email_address: "somedude@gmail.com",
        status: "subscribed",
      })
    }).then(function(e){
        console.log('complete')
    }).catch(function(e){
        console.log("fetch error");
    })
  };

  render () {
    return(
      <div>
        <button onClick={this.sub}> subscribe </button>
      </div>
    );
  };
};
3 Answers

It took me a while to get the syntax right for this. This is an example of a working request using nodejs in a server-side-rendered reactjs app using axios.

It appears "get" requests won't work for this method because of the 401 error: MailChimp does not support client-side implementation of our API using CORS requests due to the potential security risk of exposing account API keys.

However, patch, put, and post seem to work fine.

Example (using async / await)

// Mailchimp List ID
let mcListId = "xxxxxxxx";

// My Mailchimp API Key
let API_KEY = "xxxxxxxxxxxxxxxxxxxxxxxxxxx-us12";

// Mailchimp identifies users by the md5 has of the lowercase of their email address (for updates / put / patch)
let mailchimpEmailId = md5(values["unsubscribe-email-address"].toLowerCase());

var postData = {
    email_address: "somedude@gmail.com",
    status: "subscribed"
};

// Configure headers
let axiosConfig = {
    headers: {
        'authorization': "Basic " + Buffer.from('randomstring:' + API_KEY).toString('base64'),
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    }
};

try {
    let mcResponse = await axios.post('https://us12.api.mailchimp.com/3.0/lists/' + mcListId + '/members', postData, axiosConfig)
    console.log("Mailchimp List Response: ", mcResponse);

} catch(err) {
    console.log("Mailchimp Error: ", err);
    console.log("Mailchimp Error: ", err["response"]["data"]);
}
Related