-2

I want to GET JSON from the endpoint https://api.brawlstars.com/v1/brawlers.

(https://api.brawlstars.com/v1/brawlers?Authorization="Bearer%20[My API Key]")

Here's my Code:

let url = 'https://api.brawlstars.com/v1/brawlers'
    fetch(url, {
        method: "GET",
        headers: {
            "Authorization": "Bearer **USER'S API KEY GOES HERE**"
        }
    }).then((response) => {
        let json = response.json();
        console.log(json);
    }).catch((err) => {
        console.error(err)
    });

This is the output (error):

Access to fetch at 'https://api.brawlstars.com/v1/brawlers' from origin 'http://127.0.0.1:8887' has been 
blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If 
an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS 
disabled.
sketch.js:3 GET https://api.brawlstars.com/v1/brawlers net::ERR_FAILED
127.0.0.1/:1 Uncaught (in promise) TypeError: Failed to fetch

What am I missing?

enhzflep
  • 12,927
  • 2
  • 32
  • 51
Fun Planet
  • 73
  • 1
  • 5
  • 1
    https://stackoverflow.com/questions/43871637/no-access-control-allow-origin-header-is-present-on-the-requested-resource-whe – CBroe Jun 17 '20 at 08:46
  • 1
    [Will it CORS?](https://httptoolkit.tech/will-it-cors/) – deceze Jun 17 '20 at 08:47

1 Answers1

0

In your header, you need to enable CORS like CBroe said :

  headers.append('Access-Control-Allow-Origin', 'http://127.0.0.1:8887');
  headers.append('Access-Control-Allow-Credentials', 'true');

Edit :

The server (that the POST request is sent to) needs to include the Access-Control-Allow-Headers header (etc) in its response. Putting them in your request from the client has no effect.

This is because it is up to the server to specify that it accepts cross-origin requests (and that it permits the Content-Type request header, and so on) – the client cannot decide for itself that a given server should allow CORS.

Jonathan Delean
  • 1,011
  • 1
  • 8
  • 25
  • Ok, I did that and now it says Access to fetch at 'https://api.brawlstars.com/v1/brawlers' from origin 'http://127.0.0.1:8887' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response. OOPS – Fun Planet Jun 17 '20 at 11:09