I have a problem with cors blocking my API that has driven me to my wits end.
I made a WordPress child theme using standard HTML, PHP and JavaScript. The code below is what I have on my front-page.php
The actual logic of the function must be ok because it does return the vehicle details in the console if I run Chrome without any security. However when running it in normal mode it gets the :
"Failed preflight check, access-control-allow-origin header is missing"
I understand the concept of CORS and it is because the origin server (my site) is different to the API server. But I can not figure out how to add the access-control-allow-origin:
The problem is the same either on my live server, local Mamp server or even if I just have the code in a simple single html file.
<script>
function submitReg() {
var url = "https://driver-vehicle-licensing.api.gov.uk/vehicle-enquiry/v1/vehicles";
var xhr = new XMLHttpRequest();
xhr.open("POST", url);
xhr.setRequestHeader("x-api-key", "APIKEYPLACEHOLDER");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function() {
if (xhr.readyState === 4){
console.log(xhr.status);
console.log(xhr.responseText);
}
};
var reg = document.getElementById("inputReg");
var data = JSON.stringify({"registrationNumber": reg.value});
xhr.send(data);
}
</script>
Please help...
I tried editing the HTACCESS to this but it has no effect.
Lets call the domain where the request is being sent from example.com
# BEGIN WordPress
# The directives (lines) between "BEGIN WordPress" and "END WordPress" are
# dynamically generated, and should only be modified via WordPress filters.
# Any changes to the directives between these markers will be overwritten.
Header set Access-Control-Allow-Origin "example.com"
Header set Access-Control-Allow-Credentials true
Header set Access-Control-Allow-Methods "POST, GET"
# END WordPress
I also tried adding
<?php header('Access-Control-Allow-Origin: *'); ?>
to the top of my header.php and front-page.php and neither had an effect.