1

Situation:

I want to call --> Food Hygiene API and manipulate the result, before rendering.

I believed I could write this clientside in Javascript in a single page web app, avoiding the need for a full-stack application.

I ran into the 'Cross Origin Request Blocked' and subsequently discovered the Same-Origin Policy followed by CORS.

I have subsequently tried:

A CORS request with this code (from this source):

$( document ).ready(function() {
  const ul = document.getElementById('authorities');
  const url = 'http://ratings.food.gov.uk/authorities/json'

  function createCORSRequest(method, url) {
    var xhr = new XMLHttpRequest();
      xhr.open(method, url, true);
      return xhr;
  }

  var xhr = createCORSRequest('GET', url);

  xhr.onload = function() {
    var responseText = xhr.responseText;
    console.log(responseText);
  }

  xhr.onerror = function() {
    console.log("there was an error!");
  }

  xhr.send();  
});                                                                     

A jQuery call with JSONP (that errors and returns no responseText from the target):

function getData() {
    $.ajax({
      type: "GET",
      url: 'http://ratings.food.gov.uk/authorities/json',
      accept: "text/json",
      async:true,
      contentType: 'text/plain',
      dataType : 'jsonp',   
      crossDomain:true,
      xhrFields: {
        withCredentials: false
      },
      success: function(json) {
        alert("Success");
        console.log(json);
      },
      error: function(data) {
        alert("Error");
      },
    });
  }

From what I can tell, the target api does not support CORS, as the HTTP response pushes xhr to error, in both the vanilla and the jQuery example.

Have locally 'resolved' the issue with this Chrome Extension, but I don't think that it will solve the problem for users that were to clone the repo, or use the page if it were hosted on, for example, Heroku.

What are my options from here?

Community
  • 1
  • 1
RJones
  • 41
  • 3
  • 7
  • 1
    one option only if you don't have any control of the server ... proxy the request through your own server – Jaromanda X Sep 11 '17 at 10:25
  • One thing that comes to mind is trying to set the .withCredentials property to true before sending the XMLHttpRequest reference: https://www.html5rocks.com/en/tutorials/cors/. – Mr. Reddy Sep 11 '17 at 11:25
  • Yeah, tried that but to no avail Mr Smith :/ – RJones Sep 11 '17 at 11:27
  • You can do this: `const url = 'https://cors-anywhere.herokuapp.com/ http://ratings.food.gov.uk/authorities/json'` …and it will work. For an explanation, see the *How to use a CORS proxy to get around “No Access-Control-Allow-Origin header” problems* section of the answer at https://stackoverflow.com/questions/43871637/no-access-control-allow-origin-header-is-present-on-the-requested-resource-whe/43881141#43881141 – sideshowbarker Aug 31 '18 at 15:32

0 Answers0