I know this has been asked a lot of times, but not answered well. And this shouldn't be complicated seeing as how the API is for use by anyone with a dev key.
I am trying to make a GET request to a very simple API. I can open up a web browser and enter: https://example.com/myusername/?key=myDevKeyHere&userid=1234
the remote host replies with some json like so {"userid":"1234","fname": "joe"}
Next, I create an html page with something like this javascript:
var xhr = new XMLHttpRequest(); xhr.open("GET", "https://example.com/myusername/?key=myDevKeyHere&userid=1234" , "true"); xhr.onload = function() { console.log(xhr.responseText); }; xhr.send();
and of course I get a CORS Error. ( blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.)
I understand what's going on and why I am getting the CORS Error. What I can't seem to do is find out how to properly call a remote API from my server and avoid this. I google and see lot's of people pasting the same links to CORS Documentation about how CORS works but no examples or context. (The examples I see a lot of are assuming that I am the one creating the remote API and can just add Access-Control-Allow-Origin: mySITE on the server side.)
Do I need to add some magic "xhr.setRequestHeader()" lines to the xhr Get request on my html page? Do I need to configure some Apache Directive on MY server, hosting MY page?
Some have suggested I use a proxy site for the request, some assume everyone is using node.js and tell me to use a third part library. This seems way too complicated for a simple API call. If I saw some working example of javascript to make the query, maybe things would "click" and I'd have the "ahah" moment. It seems like those with expertise with Headers and CORS have forgotten what it's like to learn this from scratch and over explain "what" and "why" about CORS leaving out the "how" and "where".