-2

I'm trying to do a simple xmlhttprequest in order to take data from a json in localhost, why it doesn't work and return Failed to load http://127.0.0.1:8080/test: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. ?

      var xmlRequest = new XMLHttpRequest();
  xmlRequest.onreadystatechange = stateChanged ;
  xmlRequest.open("GET", "http://127.0.0.1:8080/test", true);

  xmlRequest.send(null);
  console.log(xmlRequest.status);
  console.log(xmlRequest.readyState);


  function stateChanged() {
 if (xmlRequest.readyState == 4) {
  if (xmlRequest.status == 200) {
    message = "Text: " + xmlRequest.statusText + "nn" ;
    message += "Headers:n" +xmlRequest.getAllResponseHeaders() + "n" ;
    message += "Response:n" + xmlRequest.responseText ;
    alert(message) ;
    } else { alert("Error receiveing the XML data") ; }
  }
}
Mark Baijens
  • 13,028
  • 11
  • 47
  • 73
Grazia Bo
  • 15
  • 6
  • Here is some documentation for you: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS – sjahan Sep 25 '18 at 10:19
  • Here is previous SO same exact question https://stackoverflow.com/questions/20035101/why-does-my-javascript-get-a-no-access-control-allow-origin-header-is-present – Zyigh Sep 25 '18 at 10:21

1 Answers1

0

In order to be able to query that URL, you need to set up your web server to send appropriate 'CORS' (Cross Origin Resource Sharing) HTTP headers.

When the browser attempts to make the request, its internal security settings block the request.

You should adjust your web server by adding in a 'middleware' that sends appropriate CORS headers, usually by responding to an OPTIONS request.

stef
  • 14,172
  • 2
  • 48
  • 70