首页 > 解决方案 > 如何使用 Fetch API 进行 GET 请求

问题描述

我想从端点https://api.brawlstars.com/v1/brawlersGET获取JSON 。

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

这是我的代码:

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)
    });

这是输出(错误):

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

我错过了什么?

标签: javascriptapifetch

解决方案


在您的标题中,您需要像 CBroe 所说的那样启用 CORS:

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

编辑 :

服务器(POST 请求被发送到)需要Access-Control-Allow-Headers在其响应中包含标头(等)。将它们放入来自客户的请求中没有任何效果。

这是因为由服务器指定它接受跨域请求(并且它允许 Content-Type 请求标头等)——客户端无法自行决定给定服务器应该允许 CORS。


推荐阅读