javascript - 为什么 CORS 发布请求在一种情况下有效,但在另一种情况下无效

标签 javascript html cors

我正在尝试将电子邮件添加到 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/

相关文章:

javascript - 音频不播放(在 iOS、Safari 和 Chrome 上使用 HowlerJs)

javascript - 每 x 秒触发一个函数

javascript - 为什么背景颜色闪烁而不是平滑变化?

javascript - 为什么允许 'src' 属性链接到来自外部域的脚本,而 XmlHtppRequests 不允许?

php - CORS 飞行前请求返回 "403 Forbidden";随后的请求然后只在 Chrome 中发送

javascript 正则表达式匹配所有自定义注释掉的部分,但不匹配其他文本

javascript - 根据 iFrame 内容自定义自己的页面?

html - 基于 2 div 的百分比高度

javascript - 如何替换 div id 中的类名?

jquery - 仅限 Chrome 中的超慢预检选项