-1

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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • 1
    The server-side code you're showing... Is this the code running at `driver-vehicle-licensing.api.gov.uk`? (Because if you're in charge of a *government* website then I'd caution against changing security restrictions without a more rigorous process...) – David Jul 13 '23 at 18:22
  • Oh no lol I'm not in charge of the dvla api. I just recently requested an access token so I could make a website that looks up reg numbers and returns vehicle info. I'm new to API's though and this is my first time working with them. Before this I have only made child themes in wordpress that used basic javascript and php. Would it be right to say that the htaccess doesn't make any change if its on my server, or would that have to be done on the api server? – user3512002 Jul 13 '23 at 18:29
  • *"Would it be right to say that the htaccess doesn't make any change if its on my server, or would that have to be done on the api server?"* - Correct. If the server **being contacted** doesn't explicitly allow cross-origin requests, major browsers will by default disallow the request. An alternative approach would be to proxy the requests through your server. So your **server-side** code can expose an API endpoint which receives the request, makes its own request to the 3rd party API, and passes along the response back to the client. – David Jul 13 '23 at 18:32
  • 1
    The statements "*I understand the concept of CORS*" and "*I can not figure out how to add the access-control-allow-origin:*" are *assuredly* in direct contravention to each other. The target server must set the headers in question correctly to allow this functionality to work cross-domain; in this particular scenario, it would seem to me the target API has been deliberately configured (probably for good reason) to disallow random sites hitting their API on behalf of users. You'll need a back end of your own to proxy the requests to the target system on your users' behalf, at the very least. – esqew Jul 13 '23 at 18:32
  • I have explored trying to set up a proxy on my server that can handle it but I'm a bit of a novice here and everytime I tried linking it I would get a 404 error on the proxy. – user3512002 Jul 13 '23 at 18:35
  • I think I will have to make a proxy though, but at least I'm not going down the wrong path anymore, so thank you very much for your help. – user3512002 Jul 13 '23 at 18:42

1 Answers1

-1

I'm not a genius but I'm gonna try to put some info here.. basically your backend will handle the cors error .. they need to allow your address or domain for all of their apis.. even I had this in my recent project where.. login api was working well but later when I sent adding JWT as bearer token it was giving cors .. they changed it in some configuration files and it started working so .. yeah front end has got nothing to do with it

Manoj HT
  • 54
  • 7
  • This does not answer the question as posed. Your assertion that "*front end has got nothing to do with it*" is objectively incorrect. – esqew Jul 13 '23 at 18:34