Search code examples
javascriptjsoncorsfetch-api

Problem fetching external API returning JSON


I'm having issues fetching an external API who should return JSON.

The API doesn't have CORS enabled so I'm trying to use fetch with the option mode: "no-cors". I tried to use jsonp but doesn't work at all.

So here's the piece of code:

fetch(APIURL, {
  mode: "no-cors",
}).then(response => {
  console.log(response)
  return response.json();
}).then(data => {
  console.log(data);
}).catch(err => {
  console.log(err)
});

The catch statement returns this:

SyntaxError: "JSON.parse: unexpected end of data at line 1 column 1 of the JSON data"

Here's the result of console.log(response)

bodyUsed: true
headers: Headers
   <prototype>: HeadersPrototype { append: append(), delete: delete(), get:   get(), … }
ok: false
redirected: false
status: 0
statusText: ""
type: "opaque"
url: ""
<prototype>: ResponsePrototype { clone: clone(), arrayBuffer: arrayBuffer(), blob: blob(), … }

But in the network tab I can see the JSON response that I want to use so I find it weird that I can see it in there so I assume the problem is on my end. I tried validating the JSON output in a validator and it's a valid JSON.

Any Ideas?


Solution

  • Under normal circumstances, you cannot read data from a third party site due to the Same Origin Policy.

    CORS allows the third party site to grant your JavaScript permission to read the data.

    The no-cors setting is a means for your JavaScript to say "I do not want to do anything that requires permission from CORS". This lets you make a request to send data without being able to read the response (the benefit is that it avoids throwing an error message all over the developer console telling you that you can't read the data you aren't trying to read).

    Since you need to read the data, you cannot use no-cors.

    Since the site doesn't provide permission with CORS, you cannot read the data directly with client-side code.

    Use a proxy.