首页 > 解决方案 > 跨域请求在发送 post 请求时被阻止

问题描述

我有 2 个服务器和 2 个域我想从一个域向另一个域发送一个发布请求,但我的浏览器显示错误

从源“ https://www.example2.com ”访问“ https://example.com ”上的 XMLHttpRequest已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:“当请求的凭据模式为“包含”时,响应中的 Access-Control-Allow-Origin 标头不得为通配符“*”。XMLHttpRequest 发起的请求的凭证模式由 withCredentials 属性控制。

我用来发送发布数据的 javascript 代码是

<script>
var data = JSON.stringify({
  "key": "value sent"
});
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
  if (this.readyState === 4) {
    console.log(this.responseText);
  }
});
xhr.open("POST", "https://example.com");
xhr.setRequestHeader("content-type", "application/json");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.send(data);
</script>

所以我的问题是如何解决这个问题并将 Post 请求发送到另一个域以及使用哪种方法发送 post 请求

标签: javascriptxmlhttprequest

解决方案


您需要在服务器上启用 CORS。在 NodJs 的情况下,您可以执行以下操作:

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

app.post('/', function(req, res, next) {
  // request from other domain will work here
});

在浏览器使用

function createCORSRequest(method, url) {
  var xhr = new XMLHttpRequest();
  if ("withCredentials" in xhr) {
    xhr.open(method, url, true);
  } else if (typeof XDomainRequest != "undefined") {
    xhr = new XDomainRequest();
    xhr.open(method, url);
  } else {
    xhr = null;
  }
  return xhr;
}

推荐阅读