-1

I know this issue has been asked before but I'm having trouble really understanding what the issue is or exactly how to fix it. I'm fairly new to JavaScript and I'm trying to mess around with this API. I'm first just trying to grab the title of a game and display it in the console when I click a button. Whenever I click the button, in the console I receive:

"CORS header ‘Access-Control-Allow-Origin’ missing"

as well as:

"TypeError: NetworkError when attempting to fetch resource."

scripts.js

function getGame() {
    fetch('https://zelda-api.apius.cc/api/games')
        .then(function (response) {
            return response.json();
        })
        .then(function(data) {
            // appendData(data);
            console.log(data)
        })
        .catch(function (err) {
            console.log('error: ' + err);
        });
}

I've tried doing variations like:

fetch('https://zelda-api.apius.cc/api/games'{
    mode: 'cors', 
    headers: {'Access-Control-Allow-Origin': '*'}
})

Again, I know this isn't a new problem but I'm having trouble adapting all the other answers to my situation. I appreciate the help!

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

1 Answers1

0

If you check the error message from browser carefully, you will find that the header you mentioned should be in the response header. It means, you cannot control the CORS rules from the frontend code. This mechanism is used to keep the important informantion that api provides should only be get from the real site who owns the right dns. You can check more details about this topic here

ldwformat
  • 21
  • 4
  • Ok sorry if this is a dumb question but does that mean i’d have to set up a node server or something and define the headers there? – danibarstad Feb 25 '21 at 06:21
  • or is this something the creator of the API has to do? – danibarstad Feb 26 '21 at 04:11
  • There are some options you can pick to solve this issue, and yes, setting up a forward server is a common way. A backend server(made by nodejs or any other programming language) can get the resource from the origin site then forward the origin response to your frontend. @TheInternetDani – ldwformat Feb 26 '21 at 05:07