我有 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/