javascript - 如何使用 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
我错过了什么?
解决方案
在您的标题中,您需要像 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。
推荐阅读
- excel - 使用 1 个电子表格更新多个 MS ACCESS 表
- php - 有人可以解释 call_user_func_array(array(arg1, arg2), []) 是如何工作的吗?
- installshield - 有没有办法查看 InstallShield 中是否使用了 PATH 变量?
- azure-devops - Teamcity 无法从 Vsts 添加 VCS 根目录
- html - 使用 python 3.x beautiful soup 和 urrllib.request 抓取数据
- angular - 从 Angular 5 返回 CSV 文件
- aws-lambda - Aws lambda 函数多个 jar 与单个 jar
- azure-iot-central - 复杂遥测可视化和处理
- amazon-web-services - AWS VPC 终端节点 IPV4 连接和 IPV6 连接
- google-cloud-platform - 直接访问 Google Cloud SQL 还是通过 pub 子队列访问?