javascript 设置头访问控制允许源

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48263526/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:03:31  来源:igfitidea点击:

javascript set header Access-Control-Allow-Origin

javascriptxmlhttprequestrequest-headers

提问by Fczanardo

I'm testing JS with POST. But I didn't get success with that.

我正在用 POST 测试 JS。但我没有成功。

Using the code:

使用代码:

<!DOCTYPE html>
<html>
<body>

<div>
testing js...
</div>

<script>
function upload() {
    var method = "POST";
    var url = "http://127.0.0.1:9000/push";

    var xhr = new XMLHttpRequest();

    xhr.open(method, url);

    xhr.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
    xhr.setRequestHeader("Access-Control-Allow-Origin", "*");

    var text = {"command":"PUSH"};
    xhr.send(text);

}         
upload();
</script>

</body>
</html>

I'm getting the following error:

我收到以下错误:

enter image description here

在此处输入图片说明

The weird is that the request header is not being set correctly through the line:

奇怪的是,请求标头没有通过以下行正确设置:

xhr.setRequestHeader("Access-Control-Allow-Origin", "*");

The request header is like this:

请求头是这样的:

enter image description here

在此处输入图片说明

回答by Mosè Raguzzini

Look at the XHR response: Access-Control-Allow-Origin IS present, Origin is null because you are executing it from your local system, upload to a server to see origin populated.

查看 XHR 响应:Access-Control-Allow-Origin IS 存在,Origin 为空,因为您是从本地系统执行它,上传到服务器以查看填充的原点。

function upload() {
    var method = "POST";
    var url = "http://127.0.0.1:9000/push";

    var xhr = new XMLHttpRequest();

    xhr.open(method, url);

    xhr.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
    xhr.setRequestHeader("Access-Control-Allow-Origin", "*");

    var text = {"command":"PUSH"};
    xhr.send(text);

}

$(document).ready(function(){
$('.upload').click(upload);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button class="upload">Upload</button>