【问题标题】:how do I make a post and get request with ReactJS, Axios and Mailchimp?如何使用 ReactJS、Axios 和 Mailchimp 发布帖子并获取请求?
【发布时间】:2017-12-05 01:32:31
【问题描述】:

我是 ReactJS 的新手,我正在尝试构建这个需要使用 mailchimp 的应用程序,以便用户可以订阅时事通讯。我需要使用 axios 发出请求吗?有人可以指导我吗?我在哪里放我的 api 密钥?我在下面的代码中做对了吗?我将我的 mailchimps 用户名放在“用户名”中,将我的 apikey 放在“xxxxxxxxxxxxxxxxxxx-us16”中,但是,我收到 401 错误说未经授权,但我的控制台确实说 Fetch Complete: 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: "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>
    );
  };
};

【问题讨论】:

  • 你能解释一下你什么时候想提出请求吗?并为您的问题提供一些示例。
  • 请再检查一遍
  • 您能否也发布来自 mailchimp 的确切错误消息?

标签: javascript reactjs mailchimp


【解决方案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: "somedude@gmail.com",
    status: "subscribed",
  },
  auth: {
    'user': 'username',
    'pass': 'xxxxxxxxxxxxxxxxxxx-us16'
  })
})

【讨论】:

  • @dg2903 我已经更新了我的代码并删除了不必要的位。如果可行,你可以试试吗?
  • 仍然是错误 401。他们在文档中说:MailChimp 不支持使用 CORS 请求的 API 客户端实现,因为暴露帐户 API 密钥存在潜在的安全风险。这与错误有什么关系吗?我用纯 reactjs 写这个
  • 我明白了。这就说得通了。在客户端执行此操作将公开您的 API 密钥。这应该在您的后端完成。
【解决方案2】:

您可以使用那里描述的方法: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 可以从一天到另一天删除它,因为它没有记录,所以如果你可以避免它,你最好这样做。

【讨论】:

  • 假期回来后我会试试这个。我相信我可能已经尝试过这种方法,但它没有用,也许我做错了什么。该文件确实说他们不再允许我们使用客户端实现进行任何请求调用,它需要一个后端。我回来后会再试一次。
  • 我在回答之前试过了,对我来说效果很好。祝你好运。
  • @TimDau 您需要使用 jsonp,如那里所述。我会更新答案。 stackoverflow.com/questions/8425701/…
【解决方案3】:

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

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

但是,patch、put 和 post 似乎都可以正常工作。

示例(使用异步/等待)

// 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"]);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-20
    • 2020-06-20
    • 2018-10-30
    • 1970-01-01
    • 2020-07-17
    • 2020-11-05
    • 2019-02-15
    • 1970-01-01
    相关资源
    最近更新 更多