javascript - 发送 post 请求时跨源请求被阻止

标签 javascript xmlhttprequest

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

access to XMLHttpRequest at 'https://example.com' from origin 'https://www.example2.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

我用来发送帖子数据的 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 请求

最佳答案

您需要在您的服务器上启用 CORS。如果是 NodJ,你可以这样做:

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;
}

关于javascript - 发送 post 请求时跨源请求被阻止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53594836/

相关文章:

javascript - Meteor.call() 将 js 对象格式化为正确的剩余查询

javascript - Express 上 Jade 模板继承与外部模块的好策略

javascript - 如果我从外部脚本更改表,表排序器分页不会更新

javascript - 以 HTML 格式显示 CSV 文件

javascript - 当找不到使用 XMLHttpRequest() 的文件时如何停止 while 循环?

javascript - 如果数据参数包含-(连字符)符号如何处理?

javascript - XMLHttpRequest 抛出错误responseXML = null,但内容仍然出现

javascript - 您如何找到起始标记或结束标记的(字符串)长度?

javascript - 使用 JSON xmlHttprequest 从 Web 服务器读取数据库并显示数据?

typescript - ionic 2 无 'Access-Control-Allow-Origin' header