Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript Create a Reusable Fetch Function

tomd
tomd
16,701 Points

No 'Access-Control-Allow-Origin' when using fetch

I don't really understand whats happening. But I keep getting this error and the images won't load. Here is all my JS code

const select = document.getElementById('breeds');
const card = document.querySelector('.card'); 
const form = document.querySelector('form');

// ------------------------------------------
//  FETCH FUNCTIONS
// ------------------------------------------

function fetchData(url){
  return fetch(url)
          .then(res => res.json());
}

fetchData('https://dog.ceo/api/breeds/list')
  .then( data => generateOptions(data.message));

fetchData('https://dog.ceo/api/breeds/image/random')
  .then(data => generateImage(data.message));


// ------------------------------------------
//  HELPER FUNCTIONS
// ------------------------------------------

function generateOptions(data){
  const options = data.map( item => `
    <option value="${item}">${item}</option>
  `).join('');
  select.innerHTML = options;
}

function generateImage(data){
  const html = `
    <img src="${data}" alt>
    <p>Click to view images of ${select.value}s</p>
  `;
  card.innerHTML = html;
}

function fetchBreedImage(){
  const breed = select.value;
  const img = card.querySelector('img');
  const p = card.querySelector('p');

  fetchData(`https://dog.ceo/api/breed/${breed}/images/random)`)
    .then(data => {
      img.src = data.message;
      img.alt = breed;
      p.textContent = `Click to view more ${breed}s`;
    })
}

// ------------------------------------------
//  EVENT LISTENERS
// ------------------------------------------

select.addEventListener('change', fetchBreedImage);
card.addEventListener('click', fetchBreedImage);

// ------------------------------------------
//  POST DATA
// ------------------------------------------

2 Answers

Ari Misha
Ari Misha
19,268 Points

Hello there! By default, Fetch API is restricted to the same origin policy. Browsers restrict scripts to access the URL 'coz of the safety issues and the same could be done by the Hackers to crawl or access any endpoint for the sensitive data. In order to use fetch for with CORS(Cross-Origin Policy) , you're gonna have to send custom headers with your fetch. It should look something like this:

fetch(someUrl, { mode: 'cors' }).then()

In the above syntax, the additional object is called as options object where you can provide additional Headers or options about the fetch API should work. You can also use { mode: 'no-cors' } for opaque responses.

I hope it helped!

~ Ari

tomd
tomd
16,701 Points

I found the problem, there is a parentheses in my template literal.