javascript set header Access-Control-Allow-Origin [duplicate]

帅比萌擦擦* 提交于 2020-08-07 06:10:12

问题


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

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


回答1:


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.

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>


来源:https://stackoverflow.com/questions/48263526/javascript-set-header-access-control-allow-origin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!