GET JSON with XMLHttpRequest

GET JSON with XMLHttpRequest

本文关键字:XMLHttpRequest with JSON GET      更新时间:2023-09-26

我有一个生成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代码时,它不会运行。你能帮我了解我在这里做错了什么吗?

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