2

When I try to fetch JSON from Tibia API I am getting two things.

Error: tibia.js:8 Uncaught (in promise) SyntaxError: Unexpected end of input

Warning: Cross-Origin Read Blocking (CORB) blocked cross-origin response https://api.tibiadata.com/v2/characters/Burdeliusz.json

class Tibia {
    constructor() {}
    async getCharacter(char) {
        const characterResponse =
            await fetch(`https://api.tibiadata.com/v2/characters/${char}.json`, {
                mode: 'no-cors'
            });
        const character = await characterResponse.json();
        return {
            character
        }
    }
}

I searched similar questions, but I couldn't find the fix.

Rahul Sharma
  • 9,534
  • 1
  • 15
  • 37
D.Wasilewski
  • 119
  • 3
  • 3
  • 12
  • Any fetch request made with `{mode:'no-cors'}` will result in an opaque reply, which means you can't use `res.json()` or `.text()` or dot-anything. From MDN; _In addition, JavaScript may not access any properties of the resulting Response._ https://developer.mozilla.org/en-US/docs/Web/API/Request/mode – TJBlackman Aug 09 '18 at 20:07
  • So, there's no way i can fetch data from this API? – D.Wasilewski Aug 09 '18 at 20:20
  • 2
    See my answer, you can access it using a proxy. See http://jsfiddle.net/RouzbehHz/b95vcdhm/2/ (Give it a second, tibiadata.com has a pretty slow response) – Rouzbeh Hz Aug 09 '18 at 20:22
  • Yeah, you'll need to use a proxy (boo... but works) or spin up your own backend server to get the data for you. If you just need it quick and dirty, go for the proxy. – TJBlackman Aug 09 '18 at 20:26
  • @RouzbehHz after putting proxy i got such error: TypeError: blob.json is not a function – D.Wasilewski Aug 09 '18 at 20:42
  • @RouzbehHz Everything is working fine, thanks! :D – D.Wasilewski Aug 09 '18 at 20:50
  • 1
    @D.Wasilewski Awesomeo! Glad I can help, happy coding! :) – Rouzbeh Hz Aug 09 '18 at 20:51
  • Btw, there is no good reason to use a `class` here. It has no state, it has no members, it has only a single method: just write a plain `async function tibiaGetCharacter(char) { … }` – Bergi Aug 10 '18 at 09:49

1 Answers1

0

It's because the endpoint is not passing the right params in the response header.

Header should include:

"Access-Control-Allow-Origin" : "*", 
"Access-Control-Allow-Credentials" : true 

I tested with Postman and the response had 8 headers: https://api.tibiadata.com/v2/characters/Burdeliusz.json

Connection →keep-alive
Content-Length →683
Content-Type →application/json; charset=utf-8
Date →Thu, 09 Aug 2018 20:05:30 GMT
Server →nginx/1.10.3
Strict-Transport-Security →max-age=63072000; includeSubdomains; preload
X-Content-Type-Options →nosniff
X-Frame-Options →DENY

Example of Access Control Allow Origin: https://api.spacexdata.com/v2/launches

Access-Control-Allow-Origin →*
CF-RAY →447cd76c595fab66-YYZ
Connection →keep-alive
Content-Encoding →gzip
Content-Type →application/json; charset=utf-8
Date →Thu, 09 Aug 2018 20:06:08 GMT
Expect-CT →max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
Server →cloudflare
Set-Cookie →__cfduid=d1dce3c5d11de37f960c7b47dc4f7d6701533845168; expires=Fri, 09-Aug-19 20:06:08 GMT; path=/; domain=.spacexdata.com; HttpOnly; Secure
Strict-Transport-Security →max-age=15552000; includeSubDomains
Transfer-Encoding →chunked
Vary →Accept-Encoding, Origin
X-Cache-Status →EXPIRED
X-Content-Type-Options →nosniff
X-DNS-Prefetch-Control →off
X-Download-Options →noopen
X-Frame-Options →SAMEORIGIN
X-Response-Time →151ms
X-XSS-Protection →1; mode=block

You can try asking the tibiadata people to add the headers

OR

Use a proxy to access the endpoint: http://jsfiddle.net/RouzbehHz/b95vcdhm/2/

var proxyUrl = 'https://cors-anywhere.herokuapp.com/',
    targetUrl = 'https://api.tibiadata.com/v2/characters/Burdeliusz.json'
fetch(proxyUrl + targetUrl)
  .then(blob => blob.json())
  .then(data => {
    console.table(data);
    document.querySelector("pre").innerHTML = JSON.stringify(data, null, 2);
    return data;
  })
  .catch(e => {
    console.log(e);
    return e;
  });

You can recreate the proxy server:

git clone https://github.com/Rob--W/cors-anywhere.git
cd cors-anywhere/
npm install
heroku create
git push heroku master
Rouzbeh Hz
  • 97
  • 1
  • 8