I’m currently writing a wordpress plugin which should be able to read data from an external API. So I researched how to call an API using JS and have now the following code in my plugin file:
<input type="submit" name="submit" onclick="test()" /> var xhr = new XMLHttpRequest(); xhr.open("GET", "http://api-test.handball.ch/rest/v1/clubs/"); xhr.setRequestHeader("Authorization", "Basic MyBase64EncodedAuthKey"); xhr.send();
I read the manual from this API which tells me that it’s using basic authentication and GET method. But I always get this error message:
XMLHttpRequest cannot load http://api-test.handball.ch/rest/v1/clubs/.
Response to preflight request doesn’t pass access control check: No
‘Access-Control-Allow-Origin’ header is present on the requested
resource. Origin ‘http://www.hckaltenbach.ch‘ is therefore not allowed
access. The response had HTTP status code 405.
So I googled this error message and due to my researches I added this line to my plugin.php file:
<?php header('Access-Control-Allow-Origin: *'); ?>
I also added this to my .htaccess file:
<IfModule mod_headers.c> Header add Access-Control-Allow-Origin "*" Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type" Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS" </IfModule>
But I still get the above error message. I don’t know what to try/do anymore so I hope some of you can give me a hint.