0

I kept a JSON files in Server A, ip : 111.111.111.111/folder1/a.json

From Server B [ ip : 444.444.444.444 ], I am trying to access that JSON file , I received the result below:

Access to XMLHttpRequest at 'http://111.111.111.111/a.json' from origin 'http://444.444.444.444' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I wrote the following code in 111.111.111.111/index.php , but I am receiving the same error:

<?php

Access-Control-Allow-Origin: "http://444.444.444.444"
Access-Control-Allow-Origin: *
Header set Access-Control-Allow-Origin: *

?>

Accessing JSON using below JavaScript code :

$.getJSON("http://111.111.111.111/folder1/a.json", (data) => {  }
2

Your Access-Control policy needs to be set on the same URL than the requested ressource.

What I mean is that if you're going to request access to /folder1/a.json, then the Access-Control headers needs to be set on the requests for this specific URL.

You could add these headers via your server (Apache / Nginx / ...) or create a php script like the one you made that sets those headers and returns the json file content (i.e. /folder1/a.json.php).

BTW your code isn't valid PHP, use the header(...) function.

You coud use a script like this:

<?php
    header('Access-Control-Allow-Origin: http://444.444.444.444/*');
    header('Content-Type: application/json; charset=utf-8');
    die(file_get_contents('a.json'));
?>
  • Thanks, do i need to set these codes in client or server ? means do i need to add the code in 111.111.111.111 or 444.444.444.444 – vickey colors Aug 2 at 12:05
  • PHP is server side only, so you'd need to do that on your server A. – NaviR Aug 2 at 12:06
  • thanks, so i am writing code in correct address 111.111.111.111 , do i need to add code like this : <?php Access-Control-Allow-Origin: http://111.111.111.111/folder1/a.json ?> ? – vickey colors Aug 2 at 12:08
  • Like I said you should use the header function. The allow origin header list pages that are allowed to request the current ressource, so you should add server B in the allow origin header (http://444.444.444.444/*) – NaviR Aug 2 at 12:10
  • thanks, i wrote like this : <?php header('Location: http:/444.444.444.444'); ?> – vickey colors Aug 2 at 12:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.