Search code examples
javascriptreactjsfetchcodesandbox

Javascript Fetch - How to Fix Failed to Fetch Error (probably from making HTTP request on HTTPS site?)


This is the React app (and code). It generates 3 random objects (from list of 500+ objects stored locally). I want to call IconFinder API when the random objects are chosen and just display the icons then (instead of finding 500 icons beforehand).

I'm running it on Windows 10 with Google Chrome Version 84.0.4147.89 (Official Build) (64-bit). The code is hosted on Codesandbox. You can take a look at all the code here or just the output and Chrome dev tools here

Demo XHR GET request that they show in their Docs

var data = null;

var xhr = new XMLHttpRequest();

xhr.addEventListener("readystatechange", function () {
  if (this.readyState === this.DONE) {
    console.log(this.responseText);
  }
});

xhr.open("GET", "https://api.iconfinder.com/v4/icons/search?query=arrow&count=10");
xhr.setRequestHeader("authorization", "Bearer <API KEY HERE>");

xhr.send(data);

My Fetch GET request

let url = "https://api.iconfinder.com/v4/icons/search?query=arrow&count=1&premium=0";
let h = new Headers();
h.append("Accept", "application/json");
h.append(
  "authorization",
  "Bearer <API KEY HERE>"
);
let req = new Request(url, {
  method: "GET",
  headers: h,
  credentials: "include"
});

fetch(req)
  .then(response => {
    if (response.ok) {
      return response;
    } else {
      throw Error(`Request rejected with status ${response.status}`);
    }
  })
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(err => console.error("Error: ", err.message));

Output: Console reads Error: Failed to fetch

In the Chrome Dev Tools, Network Tab (Screenshot 1) I see a file of type fetch (Screenshot 2) and file of type json (Screenshot 3 and 4) have something wrong with them.

What I've tried

  • Fetch GET requests work for Codesandbox with the Star Wars API (no authentication required), but not for MovieDB API (authentication in url not headers - ex. https://api.themoviedb.org/3/search/movi?api_key=<INSERT KEY>?<other parameters here> ). It threw an error because response.ok wasn't true.
  • I tried fetching data from the IconFinder API and the MovieDB API on other online IDEs (like Scrimba.com and repl.it). Those also didn't work.
  • I've tried using XHR requests and fetch await requests instead of fetch requests chained with then promises on different platforms. No luck.
  • I've double-checked how to set the authentication headers with the IconFinder API documentation.
  • I've also double-checked that my API key is registered to the url I'm calling it from and not restricted to any domains (Screenshot 5)
  • Looked through these Forums: it looks like I have something going wrong with making fetch requests from a HTTPS page, but I'm not sure what I need to change in my code based on that information. I've tried reloading the page on Codesandbox as http, but it redirects me to https automatically (Source 1, Source 2, Source 3, Source 4)

This is my first time making API calls so I don't really know what the possibilities are for what could go wrong and how to fix it. I've tried looking at some other StackOverflow threads but I'm having a hard time understanding them. Next, I'm going to try transferring the React App to a local file and seeing if I can make fetch requests there. Anyone have any thoughts on what else I should try?


Solution

  • The issue was based on a CORS error. A friend of mine told me to test the api call to:

    https://api.iconfinder.com/v4/icons/search?query=arrow&count=1&premium=0
    

    via https://reqbin.com/. It worked on the testing website.

    Then, he told me to just make the request to that url with this Cors Anywhere tool. Like this:

    https://cors-anywhere.herokuapp.com/https://api.iconfinder.com/v4/icons/search?query=arrow&count=1&premium=0
    

    That worked on my local development environment. Still not sure exactly HOW it works.