简体   繁体   中英

xhr request Control Origin

I am trying to get xhr request. (The script should run in a loop every 2 seconds) This is my script:

function getJson() {
            var xhr = new XMLHttpRequest();
            xhr.open("get", "http://www.oref.org.il/WarningMessages/alerts.json", true);
            xhr.onload = function(){
                var response = JSON.parse(xhr.responseText);
                checkJson(response);
            }
            xhr.send(null);

            setTimeout(arguments.callee, 2000);
}

getJson();

I am getting this error: XMLHttpRequest cannot load http://www.oref.org.il/WarningMessages/alerts.json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://klh-dev.com' is therefore not allowed access. XMLHttpRequest cannot load http://www.oref.org.il/WarningMessages/alerts.json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://klh-dev.com' is therefore not allowed access.

So I searched online and I tried to add few lines to my script but it didnt work: response.addHeader("Access-Control-Allow-Origin", "http://www.oref.org.il/WarningMessages");

response.addHeader("Access-Control-Allow-Origin", "*");

and I tried this one in external html page

header('Access-Control-Allow-Origin: *');  

Nothing worked..

You've run into a set of issue collectively known as Cross-Origin Resource Sharing (CORS). Long story short, browsers typically don't allow scripts to access servers that the script didn't originate from, unless the server explicitly allows it. Since your script's origin http://klh-dev.com is not the same as the request target http://www.oref.org.il , the browser is blocking the request.

There are two possible solutions: 1) modify the server to implement CORS headers (probably not possible unless you are in control of the server) or 2) use JSONP to execute the request (does not work in all cases). So, JSONP or CORS?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM