How can I correctly fetch the Riot API with JS?

699 views Asked by At

i've been trying to fetch some data from the riot's api, and I have a problem:

This is the important part of the code:

const getUsuario = async (name) => {
  const resp = await fetch(`${APIRUL}${name}${apikey}`, {
    method: 'GET',
    mode: 'no-cors',
    headers: {
      "Content-Type": "application/json",
    },
  });
  const { data } = await resp.json();
  return data;
};

getUsuario("user-name");

If i put mode: cors. I have a problem with CORS, but if I have as the example above, it shows up this:

champions.js:15 Uncaught (in promise) SyntaxError: Unexpected end of input
    at getUsuario (champions.js:15)

This is the line 15:

const { data } = await resp.json();
1

There are 1 answers

8
dwosk On BEST ANSWER

I found a similar error to what you are seeing here: fetch() unexpected end of input

Try printing the response before turning it to json and see if you see type opaque. This is specific to fetch requests made with mode no-cors. There seems to be a lot of restrictions to what you can do with this kind of response.

Updated: The RiotGames api server does not return the CORS headers for a reason. Most likely they don't want you to access their API directly from the browser. You need to have a backend make those api requests for you which can then forward the responses to your frontend.