CORS Access-Control-Allow-Origin

Hi,
Am trying to retrieve company number data via XMLHttpRequest() for a coding project. Am new to coding. Trying to create a webpage that on input of a company name retrieves and renders a company number. Below my code.

2 errors cropping up:

  1. Access to XMLHttpRequest at ‘https://api.companieshouse.gov.uk/companies’ from origin ‘https://8000-c6e30799-0203-472e-8101-ed7491e3ab02.ws-eu01.gitpod.io’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
    2.Failed to load resource: net::ERR_FAILED

function getData(cb) {
var request = new XMLHttpRequest();
var username = “API_Key”;
var password = “”;
request.open(‘GET’, ‘https://api.companieshouse.gov.uk/companies’, true);
request.setRequestHeader(“Authorization”, "Basic " + btoa(username + “:” + password));
request.setRequestHeader(“Content-Type”, “application/json”);
request.setRequestHeader(“Accept”, “application/json”);
request.withCredentials = true;
request.send();
console.log(request);
}

function writeToDocument(company_number) {
getData(company_number, function(data) {
document.getElementById(“data”).innerHTML = data;
});

}

Can anyone help me with this please?

This question has been asked and answered so many times here.
Please use the search functionality (top right corner) to search for ‘Access-Control-Allow-Origin’

Hi Mark,
Localhost requests are still not allowed are they? As in discussion: Allow localhost JavaScript domain?

Correct, still not allowed.

You have to understand that the CORS behavior is not an error — it’s a mechanism that’s working as expected in order to protect your users, you, or the site you’re calling. If I understood it right you are doing an XMLHttpRequest to a different domain than your page is on. So the browser is blocking it as it usually allows a request in the same origin for security reasons. You need to do something different when you want to do a cross-domain request. In this case you need to enable your service for CORS which is cross origin resource sharing.

If you want to bypass that restriction when fetching the contents with fetch API or XMLHttpRequest in javascript, you can use a proxy server so that it sets the header Access-Control-Allow-Origin to *.

If you need to enable CORS on the server in case of localhost, you need to have the following on request header.

Access-Control-Allow-Origin: http://localhost:9999