问题
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