0

I'm trying to access an API using Fetch. I can't code from scratch so I've pieced this together various sources, including the API documentation source code:

    <script type="text/javascript">

          const url = 'https://apis.apprenticeships.sfa.bis.gov.uk/vacancies/v1/apprenticeships/search?standardLarsCodes=465';

          var myHeaders = new Headers({
            'Ocp-Apim-Subscription-Key':'xxxxxxxxxxxxxxxxxxxxxxxxx',
            'Host':'apis.apprenticeships.sfa.bis.gov.uk',
            'Access-Control-Allow-Origin':'xxxxxxxxxxxxxxxxxxxxxx'
          });

          fetch(url, {
            mode: 'no-cors',
            withCredentials:true,
            headers: myHeaders
          })

          .then(function(response) {
            data: "{body}"
          })

          .catch(function(error) {
            console.log('Looks like there was a problem: \n', error);
          });

        </script>

Here's the example code provided by the API documentation (which uses Ajax in the HTML header):

    $(function() {
        var params = {
            // Request parameters
        };

        $.ajax({
            url: "https://apis.apprenticeships.sfa.bis.gov.uk/vacancies/v1/apprenticeships/{vacancyReference}?" + $.param(params),
            beforeSend: function(xhrObj){
                // Request headers
                xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","{subscription key}");
            },
            type: "GET",
            // Request body
            data: "{body}",
        })
        .done(function(data) {
            alert("success");
        })
        .fail(function() {
            alert("error");
        });
    });

When I run the code from my Wordpress site I get the following error:

Uncaught SyntaxError: Unexpected token '<'

When I run from my local test server I get:

Failed to load resource: the server responded with a status of 401 (Access Denied)

Any pointers on where I'm going wrong here?

  • Uncaught SyntaxError: Unexpected token '<' is because of a typo in your script. So check if there's a '<'. The 401 error is because you have no permissions to access the api data. The api returns the exception: Access denied due to missing subscription key. Make sure to include subscription key when making requests to an API. – Jeroen de Beer Jan 15 '20 at 14:36
  • Thanks, but I do include the subscription key in the myHeaders variable? – Neil Grant Jan 15 '20 at 14:56
  • @NeilGrant What ever it is, Jeroen is right, you have no persmissions to the API you're trying to fetch data. Check your credentials and re-read the API documentation. The unexpected token is most likely the response in HTML format, which you're trying to parse to JSON. That will fix itself when the API gives you a proper response. – Teemu Jan 15 '20 at 15:02

1 Answers1

0

So it turns out my browser needed an 'Access-Control-Allow-Origin' response header in order to access the JSON data. I'm requesting data from a third party server where I can't amend backend configuration, so I went with this solution of using a CORS proxy:

No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API