-1

I've read articles about cross-origin requests. Considering this resource link :

https://coinmap.org/api/v1/venues/?mode=list

Why I can make a request with PHP to this link and get data but I can't do same thing with ajax call? I get this error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://coinmap.org/api/v1/venues/?mode=list. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

If request is blocked, why I can request using PHP and not ajax?

Artin Artin
  • 349
  • 7
  • 16
  • 1
    Because PHP using curl (or the like) is not an ajax call. It is virtually exactly like a user with a web browser hitting a url directly... just programatically. Its a policy inside modern browsers to protect random users from malicious js code. – IncredibleHat Aug 03 '20 at 17:39
  • @IncredibleHat thank you so much – Artin Artin Aug 03 '20 at 17:46

2 Answers2

1

Simple Answer: The browser prevents that.

So put in your code which outputs the HTML to the browser the header:

header('Access-Control-Allow-Origin: https://coinmap.org');

and your AJAX call will be allowed to connect there.

Markus Zeller
  • 5,223
  • 2
  • 27
  • 29
  • thank you. But I didn't exactly understand your solution. At this time I'm trying to make an Ajax call from localhost to https://coinmap.org. But where should I put the code you wrote?! I don't have access to https://coinmap.org files – Artin Artin Aug 03 '20 at 17:49
  • you mean I should add this code to my PHP file that contains my Ajax call?! – Artin Artin Aug 03 '20 at 17:55
  • Yes, you need it put into that file which outputs the HTML and the code for the AJAX request. Maybe this is your index.php. If you are not sure, you could place it in your webserver config or .htaccess file on every request. But better is to place only where required. – Markus Zeller Aug 03 '20 at 18:27
1

You said that you're allowed to make the request with PHP which sounds like you have an anchor where the href=https://coinmap.org/api/v1/venues/?mode=list.

CORS only prevents requests that are initiated via javascript. Requests made due to a user clicking on an anchor tag aren't restricted via CORS.

stackhouse
  • 46
  • 2