调用Clash Royale API遇CORS问题,请求修复方案
解决Clash Royale API调用的CORS错误与TypeError问题
问题根源
Clash Royale API不允许前端浏览器直接发起跨域请求,它的权限验证机制会拒绝非服务器端的请求来源,所以你用Chrome CORS扩展也没用——API本身就拦截了这种请求。而TypeError: Cannot read properties of undefined (reading 'name')是因为请求失败后返回的data为undefined,直接访问data.name就会报错。
解决方案
1. 搭建服务器端代理(核心解决步骤)
你需要在自己的服务器上写一个代理接口,由服务器端去调用Clash Royale API,前端再请求自己的代理接口,这样既绕开了CORS限制,又能保护API密钥不被泄露(前端代码里的密钥很容易被扒走)。
下面是用Node.js + Express实现的简单代理示例:
const express = require('express'); const fetch = require('node-fetch'); const app = express(); const port = 3000; // API密钥存服务器端,避免泄露 const API_KEY = "你的实际API密钥"; const BASE_URL = "https://api.clashroyale.com/v1"; // 前端请求这个代理接口 app.get('/api/player', async (req, res) => { try { const playerTag = req.query.tag; const encodedTag = encodeURIComponent(`#${playerTag}`); const apiUrl = `${BASE_URL}/players/${encodedTag}`; const response = await fetch(apiUrl, { headers: { 'Authorization': `Bearer ${API_KEY}` } }); const data = await response.json(); res.json(data); } catch (error) { res.status(500).json({ error: '请求失败' }); } }); app.listen(port, () => { console.log(`代理服务器运行在 http://localhost:${port}`); });
前端代码修改为请求代理接口:
fetch('http://localhost:3000/api/player?tag=89GU9VUQJ') .then((response) => { // 先判断请求是否成功 if (!response.ok) { throw new Error('请求失败'); } return response.json(); }) .then((data) => { const dataContainer = document.getElementById("data-container"); // 先确认数据存在再渲染 if (data && data.name) { const htmlContent = ` <h2>玩家信息</h2> <p>${data.name}</p> `; dataContainer.innerHTML = htmlContent; } else { dataContainer.innerHTML = '<p>获取玩家信息失败</p>'; } }) .catch((error) => { console.error(error); document.getElementById("data-container").innerHTML = '<p>请求出错,请稍后重试</p>'; });
2. 前端错误处理优化(避免TypeError)
不管用不用代理,都要在前端代码里增加错误判断,防止因请求失败导致的undefined访问错误:
- 先通过
response.ok判断请求是否成功 - 访问
data.name前先确认data和data.name是否存在
关键注意事项
- 绝对不要把API密钥写在前端代码里,任何人都能通过浏览器开发者工具看到,会导致密钥被盗用、API调用额度被刷爆。
- Clash Royale API的玩家标签需要编码(比如
#89GU9VUQJ转成%2389GU9VUQJ),上述代理代码已用encodeURIComponent处理了该问题。
内容的提问来源于stack exchange,提问作者Никой Никоев
相关产品推荐
相关产品推荐

