javascript - 跨域请求在发送 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 请求
解决方案
您需要在服务器上启用 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;
}
推荐阅读
- angular - 多个惰性模块中的惰性单例服务
- python - 如何使用 Spotipy 库按流派和年份检索曲目?
- javascript - 从 HTML 表格的同一行中的输入元素中获取值
- python - UnicodeDecodeError:“utf-8”编解码器无法解码位置 2 的字节 0xbe:无效的起始字节
- oracle - 这个查询看起来很笨拙。有一个更好的方法吗?
- python - 使用 WRF (netCDF) 数据优化阵列平面 (POA) 辐照度计算
- c++ - tensorflow::Tensor 的 flat 方法以什么顺序返回数据?
- excel - 如何在Excel中相对于对象定位表格
- swift - 检查应用程序中端口在哪个服务器上打开
- sql - 在 PostgreSql 中查找包含字符串的第一个数组值