我正在尝试将电子邮件添加到 mailchimp 帐户,但我还尝试在收集电子邮件后使用 javascript 做一些其他事情,这是我的 javascript:
function addEmail(){
var request = new XMLHttpRequest();
request.open('POST', 'https://EXTERNAL_URL', true);
var data = document.getElementById("mce-EMAIL").value;
request.send("EMAIL=" + data);
}
我得到标准的请求资源上不存在“Access-Control-Allow-Origin” header 。错误
但是当我通过 HTML 表单提交来完成此操作时,我没有收到错误,下面是我的 HTML:
<form action="https://EXTERNAL_URL" method="POST" id="mc-embedded-subscribe-form"
name="mc-embedded-subscribe-form">
<div id="mc_embed_signup_scroll" class="info-title-small">
<input type="email" name="EMAIL" id="mce-EMAIL">
<div style="position: absolute; left: -5000px;">
<input type="text" name="b_77582e128704b86e538075b23_47bb2d7f84" tabindex="-1">
</div>
<div class="clear">
<input type="submit" value="add me" name="subscribe" id="mc-embedded-subscribe">
</div>
</div>
</form>
发生什么事了?
最佳答案
same-origin policy主要涉及 JavaScript(或其他浏览器端编程语言)读取服务器对客户端请求的响应。您的表单提交不会违反同源策略,也不会因为不处理服务器响应而被阻止。
根据MDN :
Cross-origin writes are typically allowed. Examples are links, redirects and form submissions. Certain rarely used HTTP requests require preflight.
Cross-origin embedding is typically allowed.
Cross-origin reads are typically not allowed, but read access is often leaked by embedding. For example, you can read the width and height of an embedded image, the actions of an embedded script, or the availability of an embedded resource.
关于javascript - 为什么 CORS 发布请求在一种情况下有效,但在另一种情况下无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50224082/