1

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();
Knarf
  • 35
  • 1
  • 1
  • 9

1 Answers1

1

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.

dwosk
  • 1,202
  • 8
  • 11
  • I if do resp.text() I get undefined, and if I print the response before turning it to json I get type opaque. I don't know that to do with that – Knarf Oct 04 '20 at 02:33
  • Are you sure about your request url is correct? Maybe there is a problem with URL/API Token parameter and you get 403 error without a body. Maybe... – Mehmet Ali Peker Oct 04 '20 at 02:35
  • 1
    @Knarf it's a CORS thing - the server probably isn't returning some CORS headers. Read this google article for a nice explanation: https://developers.google.com/web/updates/2015/03/introduction-to-fetch#response_types – dwosk Oct 04 '20 at 02:37
  • I used the same url in postman and get what I want so I think it is correct. – Knarf Oct 04 '20 at 02:38
  • Maybe your variable name is incorrect. In the code example, you written APIRUL instead of APIURL. – Mehmet Ali Peker Oct 04 '20 at 02:39
  • The browser has different restrictions than postman - are you sure you are meant to query the RiotGames api directly from the browser? As opposed to a backend that forwards the responses to your frontend? – dwosk Oct 04 '20 at 02:41
  • I wanted to test it easily in the frontend, perhaps it is mandatory to do it from the server. The documentation doesn't explain it too much. – Knarf Oct 04 '20 at 02:44
  • 1
    Yeah I'm reading elsewhere and that appears to be the case - I updated my answer. Annoying but at least you know what's wrong :) – dwosk Oct 04 '20 at 02:44