Ajax 调用 Mailchimp API 3.0 returns HTTP 501

Ajax call to Mailchimp API 3.0 returns HTTP 501

我正在尝试简单地将具有该名称的邮件地址订阅到 MailChimp 列表。 我认为这应该很容易,但我无法post那里的邮件地址。

您可以在此处找到完整代码 (key=authkey):

$(document).ready(function(){
    $('#blogsignup').submit(function(event){
        event.preventDefault();

        $.ajax({
            url : "https://us12.api.mailchimp.com/3.0/lists/247e2f0702/members/",
            dataType : "json",
            headers: { "Content-Type":"application/json", 'Access-Control-Allow-Origin': '*', "Accept": "application/json", "Authorization": "key-us12" },
            type : 'POST',
            contentType: "application/json",
            data :  {
                apikey: "key", 
                email_address: $('#TBemail').val(),
                status: 'subscribed',            
                merge_fields: {
                    FNAME: "subscriberFirstName",
                    LNAME: "subscriberLastName"
                }
            },
            // Try to send also before
            beforeSend: function(xhr) { xhr.setRequestHeader("Authorization",
                "Basic " + btoa("api:" + "key-us12")); 
            },                  
            success : function (data) {
                $('#signup').html("Thanks for signing up. We will contact you as fast as possible.");
            },
            error : function (data, errorThrown) {
                alert(errorThrown);
                console.log(data);
            }
        });
    });
});

点击提交按钮触发函数。 我总是收到警报 "error",它说

XMLHttpRequest cannot load https://us12.api.mailchimp.com/3.0/lists/247e2f0702/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://preprod.travelgap.io' is therefore not allowed access.

响应的 HTTP 状态代码为 501。

我也在尝试 jsonp 作为数据类型,然后我收到 401 错误。 Authkey 未通过。

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

这意味着不允许客户端(进行 AJAX 调用)直接点击 API。您当前的架构:

Client (any origin) ---> MailChimp API

按照建议,您应该做的是使用您的服务器将请求代理到远程 API,这样您就不会违反他们的 CORS 规则。您应该在服务器上添加一个 API 端点,当客户端访问该端点时,它会向 MailChimp API.

发出服务器端网络请求
Client (any origin) ---> Server (known, whitelisted origin) ---> MailChimp API

此外,您的 API 密钥永远不应存在于客户端代码中。您的 API 密钥应被视为仅在服务器端可用的秘密。后一种架构确保了这种情况。