How to structure a URL to retrieve JSON data from an API using the fetch method

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)
});

Answer №1

If you're in need of assistance, I stumbled upon this helpful answer -Dealing with 'Access-Control-Allow-Origin' issue when trying to retrieve data from a REST API

To address the problem, I made these changes in my code and successfully retrieved the expected JSON response:

const proxyurl = "https://cors-anywhere.herokuapp.com/";
const url = "http://collections.anmm.gov.au/collections/json"; // website without Access-Control-* header
fetch(proxyurl + url) 
.then(response => response.json())
.then(contents => console.log(contents))

.then(function(data){

  let authors = data.results;
console.log(authors);
  return authors.map(function(author){

    let card = createNode('div'),
        h1 = createNode('h1');

        card.setAttribute('class', 'card');
    
    h1.innerHTML = `${author.name.first} ${author.name.last}`; 

    append(card, h1);
    append(div, card);

  })
})


.catch(() => console.log("Cannot access " + url + "'s response. Is it blocked by the browser?"))

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

An error has occurred during runtime due to a TypeError: The application is unable to access properties of an undefined object, specifically 'Upload'. This error has

Greetings to the amazing Stack Overflow Community! Currently, I'm developing a Next.js application that requires me to upload videos to Vimeo. To achieve this functionality, I've implemented tus-js-client for handling the uploads. However, I&apo ...

Retrieving information from a virtual document in a 'pre' save hook using Mongoose

Seeking help with utilizing data from a recently created document to update a value using a 'pre' hook. An example of the model being used: ... title: { type: String, required: true }, company: { type: mongoose.Schema.ObjectId, ref: &ap ...

Is the file corrupt using node.js?

Looking for ways to determine if a file is corrupted using node.js? I have attempted various File System methods, such as fs.readFile, fs.open, and fs.access, but all of them are showing an OK status. However, I am confident that my file is corrupted base ...

Highcharts real-time data not refreshing following modification of PHP variable

Currently, I have a live updating highchart implemented on a webpage named index.html. This highchart calls a PHP script called datatest.php to parse a CSV file, convert the data into JSON format, and then add it as a new point on the chart: $.ajax({ ...

What is the best location to initialize Firebase in a React Native application?

What is the best way to initialize Firebase in a React Native project and how can I ensure that it is accessible throughout the entire project? Below is my project structure for reference: Project Structure Here is a basic template for initializing Fireb ...

Can a collapse that was saved in a separate file be displayed on the requested page?

Imagine having a navigation bar on your website's index page with four buttons, each leading to a different page. What if you wanted to bring all those separate pages together into one by using collapsible elements? That's the challenge this user ...

Utilizing arrays in JavaScript alongside jQuery's methods such as $.inArray() and .splice()

I am currently dealing with an array that is limited to containing 12 values, ranging from 1 to 12. These values can be in any order within the array. My task is to iterate through the array and identify the first unused value, assigning it to a variable. ...

Trigger an AJAX request to execute a PHP script when a button is clicked

When I click a button, I want to run an ajax function that calls a PHP script and displays the resulting data under a specific div. However, it is not currently working as expected. Upon checking the console, I noticed that no value is being passed to the ...

Having issues with Jquery and duplicating tables functionality not functioning as expected

I am facing an issue with two external jQuery files. One file allows me to clone the last row of a table, while the other is supposed to retrieve the id of a select tag based on a class assigned to it. However, the second script only works for the original ...

Angular 7 - Issue with rendering only the "dist" folder on the browser, not the "src" folder when using nodejs

Greetings! I'm embarking on a new project involving a nodejs app with angular7. Below is the content of my mail server.js file in nodejs: var express = require('express'); var mysql = require('mysql'); var bodyParser = require(&a ...

Unable to locate any division element by using document.getElementById

I'm encountering an unusual issue in my code. I am attempting to change the background color of certain divs using Javascript, but for some reason, when I use "document.getElementById", it is unable to find the div and returns NULL. Here is the probl ...

Having trouble locating the componentwillunmountafterInteraction in the React Native deck swiper

I've been utilizing react native deckSwiper in my project, but I'm having trouble unmounting it from the screen due to an error that says "ReferenceError: Can't find variable componentWillUnmountAfterInteractions". The error stack trace is s ...

Is there a way to modify the FixedTableHeader jQuery plugin to include a fixed first column in addition to the fixed header?

I've been experimenting with a jQuery plugin I found at to create a stylish table with fixed headers, sorting options, and other interesting features. While the plugin is great, I also considered using jqGrid for its impressive capabilities. However, ...

Issue with date: date.toLocaleTimeString function is invalid

I'm currently working on creating a time display component using hooks, but I'm running into an issue with the error message "TypeError: date.toLocaleTimeString is not a function." As a newcomer to this technology, any guidance would be greatly a ...

Using an AngularJS directive to modify CSS styles

I'm attempting to modify DOM CSS styles using Angular. If the textbox value is set as the height, I have assigned ng-model to the textbox and then ng-style="{height:heightdef}" How can I achieve this using a directive? Fiddle :: http://jsfiddle.n ...

How to effectively transfer a JSON object from a Python function to JavaScript using Eel, allowing you to seamlessly utilize and modify the JSON data

Let's delve into a slightly confusing question together. Have you heard of Eel? It's a Python module that lets you use functions created in Python in Javascript, and vice versa. What I want to achieve is taking a JSON object generated by a Python ...

Preserving drop-down options in Ngx-Bootstrap Typeahead even after input is cleared

Recently, I updated my ngx-bootstrap from version 1.8.1 to 3.0.1 and encountered an issue with the typeahead functionality not working as expected. I am following this example: The issue arises when using [typeaheadMinLength]="3". When searching for "abcd ...

Unable to directly assign a variable within the subscribe() function

My goal is to fetch a single row from the database and display its information on my webpage. However, I've encountered an issue with the asynchronous nature of subscription, which prevents immediate execution and access to the data. Upon running the ...

Instructions for converting a blob URL into an audio file and securely storing it on the server

After successfully recording and adding the audio to my HTML page within the audio tag, I managed to obtain the blob source URL from the tag using the following line: var source = document.getElementById("Audio").src; The blob source URL looks ...

Creating a menu header similar to Gmail's design is a great way to

How can I create a fixed menu similar to the one in Gmail? I've attempted using CSS, but the div remains centered instead of sliding up on scroll like the Gmail menu. View in full-size image I've experimented with CSS properties, here's an ...