javascript set header Access-Control-Allow-Origin

时间:2018-01-15 12:59:18

标签: javascript xmlhttprequest request-headers

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

使用代码:

<!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>

我收到以下错误:

enter image description here

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

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

请求标头如下:

enter image description here

1 个答案:

答案 0 :(得分:1)

查看XHR响应: 存在访问控制允许原点, Origin为null,因为您从本地系统执行它,上传到服务器以查看填充的原点。

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>