Y
Y
Yaly Waidroug2018-12-28 15:37:24
CORS
Yaly Waidroug, 2018-12-28 15:37:24

ERROR ...from origin 'null' has been blocked by CORS policy: ... How to resolve?

3 days trying to deal with AJAX console issues
Access to XMLHttpRequest at ' file:///C:/OpenServer/OSPanel/domains/testo.com/ip.php ' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
ajaxGet @ script.js:9
document.querySelector.onclick @ script.js:3

index.html file

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>ТЕСТО</title>
</head>
<body>
  <input type="button" id="shop_ip" value="Show my IP">
  <div id="myip"></div>
  <script src="script.js"></script>
</body>
</html>


script.js file
window.onload = function() {
  document.querySelector('#shop_ip').onclick = function() {
    ajaxGet();
  }
}
function ajaxGet(){
  var request = new XMLHttpRequest();
    request.open('GET', 'ip.php');
    request.send();
}


ip.php file
<?php
echo $_SERVER('REMOTE_ADDR');
?>

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Stalker_RED, 2018-12-28
@Yaly

Launch some server and send requests through it, because ajax is not allowed to receive files directly.

V
vman, 2018-12-28
@vman

ip.php fix to

<?php
header('Access-Control-Allow-Origin: *');
echo $_SERVER['REMOTE_ADDR'];

go to the directory with index.html and run in the console
in the browser, type 127.0.0.1:8080

D
Dave, 2018-12-28
@djay

request.open('GET', 'ip.php');
Fix to
request.open('GET', '/ip.php');

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question