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.