Fetch API fails to fetch (typeerror) with CORS chrome extension on

I have a sample fetch API, program:

const display = document.getElementById("display");
const btn = document.getElementById("btn");
    btn.addEventListener("click", getData)


 function createNode(element) {
      return document.createElement(element);
  }

  function append(parent, el) {
    return parent.appendChild(el);
  }


function getData(){
  const ul = document.getElementById('authors');
  const url = 'https://randomuser.me/api/?results=10';
  fetch(url)
  .then((resp) => resp.json())
  .then(function(data) {
    let authors = data.results;
    return authors.map(function(author) {
      let li = createNode('li'),
          img = createNode('img'),
          span = createNode('span');
      img.src = author.picture.medium;
      span.innerHTML = `${author.name.first} ${author.name.last}`;
      append(li, img);
      append(li, span);
      append(ul, li);
    })
  })
  .catch(function(error) {
    console.log(error);
  });   
}

I get the following error in the console, whenever I click the button element to trigger the getData event.

GET https://randomuser.me/api/?results=10 net::ERR_SSL_VERSION_INTERFERENCE
index.html:53 TypeError: Failed to fetch

is this because of CORS related issues, or do I have an error in my code?

Upvotes: 1

Views: 3215

Answers (1)

front_end_dev
front_end_dev

Reputation: 2056

Check is your api returning a valid CORS header for OPTIONS request before sending actual one.

Response should contains following headers

Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST, GET,DELETE,PUT

You can read more about CORS from mozilla documentation - https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

Upvotes: 1

Related Questions