Javascript: Getting Started

I’m not 100% sure as I don’t personally use javascript to access this - all I can do is point to the other stuff on the forum:

  • I think you need use CORS (not the ‘no-cors’ - I believe CORS is the default mode but check that).
  • If you’re getting a 403 I think the issue is the domain (server) you’re making the request from is not being seen as matching one of the “Javascript domain” entries you set up in your registration. As mentioned before, if you’re on localhost there’s a hack to get around that. If not check what ports your server uses. If you’re not using 80 (for http) or 443 (for https) I think you need to specify the port somehow. Looking around the forum it seems it’s possible to add this to the JavaScript domains.
  • A good thread on this - and helpful comment - was this:

https://forum.aws.chdev.org/t/jquery-ajax-get-request/69/8

You could try using one of the jQuery examples around the forum to check if that works, then go back and make fetch() work.

Most browsers will allow you to debug this sort of thing in detail by logging network requests. This is certainly possible with Opera and Firefox out of the box and presumably Chrome too. If you switch logging on (generally in a “developer tools” section) you should be able to see the CORS process in detail. (You shouldn’t need to delve too deep since javascript / the browser should now handle all of this complexity for you in a routine manner but you might spot something here.) First you should see the browser making an http OPTIONS request. It should be possible - normally a context menu - to view or copy request or response headers, the request or response (body) or the whole lot (“copy all as HAR”). As mentioned above, what you’re looking for in your request is the “Origin” parameter. The response from the Companies House server will contain an “Access-Control-Allow-Origin” entry. If this is “*” (for everything) I think this indicates that the next step will fail for you e.g. where the browser sends the actual GET request with the Authorization header with your API key. You should see your actual specific domain there.

If you can get past that, if things are still not working again check the details, but if you’ve got a 401 error then that points to an issue with the http basic authorisation, normally due to not putting a ‘:’ after your api key, failing to run that whole string through a base64 encoding step (e.g. btoa() in javascript) or just getting the API key wrong.

1 Like