On line 10 I define a fetch request, but when I call the function the code after the fetch request and the fetch request do not run / error for some other reason. Can anyone help me bugtest this?
async function apiGet(url) {
console.log("apitest");
let response = await fetch(url);
console.log(response.ok);
}
Thank you! The reasource works without an api key (just try pasting the api link into your browser, it works as is), but I will look into the CORS error.
Loading the JSON in the browser isn’t cross-origin, fetching it from a page (like Codepen) is.
You most likely have to create a backend that uses cors and returns the JSON (sometimes called a proxy API). You would want a backend anyway if you are dealing with API keys.
Here is an example. I’m just logging the data (only works as long as the backend is running).
Here is the very quick backend
https://replit.com/@lasjorg/API-example#index.js
You can fork it if you want. I will delete the example at some point.
Edit: Just to be clear. The Codepen fork button is at the bottom of the footer and for the Replit, you can create an account and fork the example code.
BTW, I’m not sure why you are importing fetch, it is a browser API. You do not need to import anything.
It is a bit technical. I’m not even sure I can explain it well enough.
When you load the API URL in the browser it is loaded directly from the browser. When you fetch it the host that runs the fetch code is requesting a resource. The two are not the same. CORS blocking is a browser security feature.
The backend I posted has added the header using the cors package.