As a newcomer to working with APIs and data retrieval methods, I have been exploring tutorials such as this one on the fetch method or using the XMLHttpRequest
method. While I have had success with the APIs used in these tutorials, I have run into difficulties when attempting to utilize this particular API. The main issue seems to be related to the format of the URL I am using, as I keep encountering this error:
"Access to fetch at 'http://collections.anmm.gov.au/collections' from origin 'http://localhost:8888' has been blocked by CORS policy: No 'Access-Control-Allow-Origin'."
I attempted to overcome the CORS error by switching to "https," but then encountered a different error:
net::ERR_CONNECTION_REFUSED.
I noticed that I can successfully retrieve JSON data by directly entering this URL into my browser: .
My question is whether the problem lies with the specific URL I am using or if there might be an underlying issue within the API itself preventing me from accessing the data.
Below is the JavaScript code I have been working with:
function createNode(element){
return document.createElement(element);
}
function addClass(cls, el){
return el.classList.add("cls");
}
function append(parent, el){
return parent.appendChild(el);
}
const div = document.getElementById('root');
div.setAttribute('class', 'container');
//const url = 'https://randomuser.me/api/?results=100';
//can return data from this URL
const url ='http://collections.anmm.gov.au/collections' // returns data if pasted directly into the browser
//const url = 'http://collections.anmm.gov.au/collections/json' // this is the format suggested in the API documentation I think
fetch(url)
.then((resp)=> resp.json())
.then(function(data){
//create and append the list to the ul
let authors = data.results; // get results
return collections.map(function(collection){
let card = createNode('div'),
h1 = createNode('h1');
card.setAttribute('class', 'card');
img.src = collection.notes.value;
h1.innerHTML = `${collection.notes.value} ${collection.notes.value}`;
append(card, h1);
append(div, card);
})
})
.catch(function(error){
console.log(error)
});