このスニペットを使用して、ユーザーを mailchimp リストに登録しようとしています:
function subscribeUser(name, email) {
var xhr = new XMLHttpRequest();
var endpoint = 'https://<dc>.api.mailchimp.com/3.0/lists/<list>/members/';
var data = {};
data.email_address = email;
data.status = "subscribed";
data.merge_fields = {};
data.merge_fields.NAME = name;
xhr.open("POST", endpoint, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Authorization", "apikey <key>");
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
}
xhr.send(data);
}
クロムで次のエラーが生成されます。
リストを更新する ajax ベースのサービスを作成できません。皆さんが Access Control ヘッダーを追加していないためです。最新のブラウザーを使用して、単純な xhr をエンドポイントに送信できません。
XMLHttpRequest cannot load https://<dc>.api.mailchimp.com/3.0/lists/<list>/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 501.
私のサイトは静的なウェブサイトであり、そのまま維持したいと考えています。github でホストされているバックエンドは必要ありません。したがって、これに対するJSソリューションが必要です。