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
https://api.themoviedb.org/3/search/movi?api_key=<INSERT KEY>?<other parameters here>
). It threw an error because response.ok
wasn't true.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?
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.