javascript 设置头访问控制允许源 [英] javascript set header Access-Control-Allow-Origin

查看:42
本文介绍了javascript 设置头访问控制允许源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

使用代码:

<身体><div>测试js...

<脚本>函数上传(){var方法=POST";var url = "http://127.0.0.1:9000/push";var xhr = new XMLHttpRequest();xhr.open(方法,网址);xhr.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");xhr.setRequestHeader("Access-Control-Allow-Origin", "*");var text = {command":PUSH"};xhr.send(文本);}上传();</html>

我收到以下错误:

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

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

请求头是这样的:

解决方案

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

function upload() {var 方法 = "POST";var url = "http://127.0.0.1:9000/push";var xhr = new XMLHttpRequest();xhr.open(方法,网址);xhr.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");xhr.setRequestHeader("Access-Control-Allow-Origin", "*");var text = {"command":"PUSH"};xhr.send(文本);}$(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">上传</button>

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:

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:

解决方案

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>

这篇关于javascript 设置头访问控制允许源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆