如何使用ReactJS,Axios和Mailchimp发帖并获取请求?

问题描述 投票:3回答:3

我是ReactJS的新手,我正在尝试构建这个需要使用mailchimp的应用程序,以便用户可以订阅时事通讯。我需要使用axios发出请求吗?有人可以引导我通过这个吗?我把api键放在哪里?我是否在波纹管代码中更正了?我把我的mailchimps用户名放在'用户名',我的apikey放在'xxxxxxxxxxxxxxxxxxx-us16',然而,我得到401错误说未经授权,但我的控制台确实说取了完成:POST并没有发现任何错误。

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: "[email protected]",
        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>
    );
  };
};
javascript reactjs mailchimp
3个回答
1
投票

在文档中,curl示例使用--user标志。使用this将curl命令转换为等效的js代码,您需要在fetch的选项对象上使用'auth'属性才能使其正常工作。

fetch('https://us16.api.mailchimp.com/3.0/lists/xxxxxxxxx/members', {
  method: 'POST',
  headers: {
    'content-type': 'application/json'
  },
  body: JSON.stringify({
    email_address: "[email protected]",
    status: "subscribed",
  },
  auth: {
    'user': 'username',
    'pass': 'xxxxxxxxxxxxxxxxxxx-us16'
  })
})

1
投票

我花了一段时间才得到正确的语法。这是使用axios在服务器端呈现的reactjs应用程序中使用nodejs的工作请求的示例。

由于401错误:MailChimp does not support client-side implementation of our API using CORS requests due to the potential security risk of exposing account API keys.,似乎“get”请求不适用于此方法

但是,补丁,放置和发布似乎工作正常。

示例(使用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: "[email protected]",
    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"]);
}

-1
投票

你可以使用那里描述的方法:AJAX Mailchimp signup form integration

您将需要使用JSONP否则您将收到CORS错误。

如果您使用现代环境(我的意思不是jQuery),您可以使用qsqueryString等库来将表单数据转换为uri。

您的最终网址可能如下所示:

jsonp(`YOURMAILCHIMP.us10.list-manage.com/subscribe/post-json?u=YOURMAILCHIMPU&${queryString.stringify(formData)}`, { param: 'c' }, (err, data) => {
  console.log(err);
  console.log(data);
});

它有点hacky,我想Mailchimp可以将它从一天移到另一个,因为它没有记录,所以如果你能避免它,你最好这样做。

© www.soinside.com 2019 - 2024. All rights reserved.