使用JavaScript调用Brawl Stars API持续遭遇CORS错误求助
调用Brawl Stars API时遭遇CORS错误的解决方案
问题详情
我正在用JavaScript开发一个调用Brawl Stars API的项目,官方文档地址为https://developer.brawlstars.com/#/。已严格遵循文档要求检查IP地址、请求头中的Authorization信息,但始终遇到相同的CORS错误:Access-Control-Allow-Origin header is present on the request resource。
我的代码如下:
const tag = '...' const token = '...' const url = 'https://api.brawlstars.com/v1/players/%23' const options = { headers: { 'Authorization': 'Bearer'+' '+ token } } fetch(url+tag,options) .then(res => res.json()) .then(data => console.log(data))
问题原因
Brawl Stars API的服务端未配置允许前端所在域名的跨域资源共享(CORS)权限,浏览器出于安全机制会拦截这类跨域请求——这和你的代码正确性、token有效性、IP白名单配置无关。
可行解决方案
搭建后端代理(生产环境推荐)
借助自己的后端服务中转请求:由后端调用Brawl Stars API,前端再请求自己的后端接口。后端请求不受浏览器CORS限制,自然不会触发拦截。以下是Node.js + Express的简易代理示例:
const express = require('express'); const fetch = require('node-fetch'); const app = express(); app.get('/api/brawlstars/player/:tag', async (req, res) => { const token = '你的Brawl Stars API令牌'; const tag = req.params.tag; const apiUrl = `https://api.brawlstars.com/v1/players/%23${tag}`; try { const response = await fetch(apiUrl, { headers: { 'Authorization': `Bearer ${token}` } }); const data = await response.json(); res.json(data); } catch (error) { res.status(500).json({ error: error.message }); } }); app.listen(3000, () => console.log('代理服务运行在3000端口'));前端代码修改为请求代理接口:
const tag = '...' fetch(`http://localhost:3000/api/brawlstars/player/${tag}`) .then(res => res.json()) .then(data => console.log(data))使用浏览器插件临时绕过CORS(仅开发测试用)
安装如CORS Unblock这类浏览器插件,临时关闭浏览器的CORS检查。但此方法仅适用于本地开发测试,不能用于生产环境——普通用户不会为了访问你的网站特意安装这类插件。
内容的提问来源于stack exchange,提问作者Gabriel Ferreira
相关产品推荐
相关产品推荐

