【问题标题】:GET JSON with XMLHttpRequest使用 XMLHttpRequest 获取 JSON
【发布时间】:2016-07-17 06:59:06
【问题描述】:

我有一个生成 JSON 的 python 脚本,我可以在 http://192.168.1.171:17000/ 中看到它

在“网络”选项卡中,我得到了

200 GET / 192.168.1.171:17000 json transfereed 40KB

当我尝试使用 javascript 从另一个网页获取它时

var url = "http://192.168.1.171:17000";
var Httpreq = new XMLHttpRequest();

function Get(url){
    Httpreq.open("GET", url, false);
    //Httpreq.setRequestHeader( 'Access-Control-Allow-Origin', '*');
    Httpreq.send(null);
    return Httpreq.responseText;          
}

var json_obj = JSON.parse(Get(url));
console.log("data: "+json_obj);

在我得到的网络标签中

200 GET / 192.168.1.171:17000 json transfereed 0KB

这是响应标签

SyntaxError: 
    JSON.parse: unexpected end of data at line 1 column 1 of the JSON data

在控制台中

Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help http://xhr.spec.whatwg.org/ 
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://192.168.1.171:17000/. (Reason: CORS header 'Access-Control-Allow-Origin' missing). 
NS_ERROR_FAILURE: 

当我添加时

Httpreq.setRequestHeader( 'Access-Control-Allow-Origin', '*');

我没有解决问题,而是又遇到了一个错误

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://192.168.1.171:17000/. (Reason: CORS request failed).

当我访问 http://192.168.1.171:17000/ 时,我得到了我的 json,这是有效的,当我使用另一个 json 运行我的 javascript 代码时,它运行。但是当我用我的 json 运行我的 javascript 代码时,它不会运行。你能帮我理解我在这里做错了什么吗?

【问题讨论】:

  • 记住跨域错误意味着您正试图在同源(相同 IP 网络)的服务器上执行脚本。您的浏览器和服务器都在同一个 IP 网络上。尝试使用带有扩展名 Google Chrome web Server chrome.google.com/webstore/detail/web-server-for-chrome/… 的 google chrome。我将允许您从 Web 服务器启动您的 www,该服务器将查询您 192.*.*.* 上的其他服务器。网络。这对我解决跨域问题很有用

标签: javascript json xmlhttprequest


【解决方案1】:

该标头需要添加到服务器的响应中,而不是客户端的请求中。换句话说,您需要修改您的 Python 应用程序以返回 Access-Control-Allow-Origin 标头。 (具体怎么做取决于你在 Python 端使用的是什么。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-04
    • 2020-08-11
    • 1970-01-01
    • 2015-08-28
    • 2013-08-08
    • 2016-05-30
    • 2012-10-26
    • 1970-01-01
    相关资源
    最近更新 更多