0

I have a single html page which is deployed in xampp page which has a script tag where i use XMLHttpRequest to call a service url to get json data.

This only works when i call the page with http://localhost/mypage

But when i call the same page from another computer http://ipadress/mypage it throws an error.

No 'Access-Control-Allow-Origin' header is present on the requested resource

I tried using JSONP solution but that didn't work either

Note that i can only manipulate client-side code (javascript), i have no control on the service i'm calling

Why does it work with localhost but it doesn't work with ipadress?

And what are the alternative solution if there are any ?

var xhttp = new XMLHttpRequest();

xhttp.onreadystatechange = function() {

  if (this.readyState == 4 && this.status == 200) {
  
    var result = JSON.parse(this.responseText).result;
    document.getElementById("data").innerHTML = result + "%";
    
  }
};
var url = "www.url.com";
xhttp.open("GET", url + "/data.json", true);
xhttp.setRequestHeader("content-type", "application/json");
xhttp.send();
Chiller
  • 9,520
  • 2
  • 28
  • 38
  • you may take e look to this [question](https://stackoverflow.com/questions/34872760/how-do-i-enable-cross-origin-resource-sharing-on-xampp) – gaetanoM Jun 23 '18 at 21:33

1 Answers1

1

So you trying to retrieve data form a different domain than you application is actually from. You have to specify for your served page that it is allowed to do that.

Depending on how you build/serve your html page/the content (json) this is different.
Usually this is done by setting it in the header before the response is send to the client back.
Using PHP: header('Access-Control-Allow-Origin: *');
Using apache .htaccess file (for more files, eg: if you don't use server side scripts): Header set Access-Control-Allow-Origin "*"

Better would be not to specify * but the origins the application should have access to.

Further reading: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

PaulEdison
  • 897
  • 1
  • 15
  • 36
  • i tried using Header set Access-Control-Allow-Origin "*" but it doesn't work, although as i mentioned it does work when calling my page with localhost/... but when using my ip adress it gives the error – Chiller Jun 23 '18 at 21:51
  • @Chiller: Could you set the header on the target of the XMLHttpRequest target - this one is missing the header (that allows access form the IP as origin) and therefore the browser is blocking the access. Where is the target served from? Or maybe the browser sets/handles origin different on accessing via IP/local host - did you tried local via IP/remote via hostname? Maybe add these information to your question – PaulEdison Jun 30 '18 at 21:29