Hi there,
Note: I have searched the forum for related questions and only found that issues had been found and fixed in 2017. So posting this as a new topic.
I am attempting to call the GET /search/companies API using the JQuery Ajax capability, to perform a company name search.
My JavaScript is as follows:
$.ajax({
type: 'GET',
url: 'https://api.companieshouse.gov.uk/search/companies?q=' + companyName,
headers: {
'Authorization': 'Basic MY_API_KEY'
},
success: search.handleResponse,
error: search.handleError
});
When calling this using Google Chrome (Version 70.0.3538.77 - Windows 10 Pro), I get the following error in my DevTools console:
Access to XMLHttpRequest at 'https://api.companieshouse.gov.uk/search/companies?q=test' from origin 'https://MY_DOMAIN.co.uk' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Before attempting to write any Javascript, I proved out that I could call this API using POSTMAN, and was able to get a successful response and had data coming back.
Interestingly, when looking at the Network tab of DevTools, I can see 2 entries under “XHR” as a result of my single AJAX call.
Both have the same request URL as my AJAX code above, but the first has a method of OPTIONS, which returns a 204 and I can see the initator is my AJAX call. The second is a GET and returns a 200 with the expected response containing the data I am after - The initiator is marked as “Other”. I believe the GET is made as a result of a redirect from the OPTIONS request.
However, my AJAX call always fails (with the Javascript error shown above) and falls into the error block, so I am never in a position to see the successful response from the GET.
Why is there an OPTIONS request prior to the expected GET request?
What I’d like: I call the GET, receive a 200 response from the GET request, with the data I expect with no javascript errors. All with no unexpected OPTIONS request.
I have read the Companies House API docs over and over and am failing to see what I am missing.
Thanks a lot,
Ryan