You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用Clash Royale API时触发No 'Access-Control-Allow-Origin'错误求解决方案

解决Clash Royale API跨域请求错误及调用指导

问题原因

你遇到的No 'Access-Control-Allow-Origin' header错误是浏览器同源策略导致的:Clash Royale API服务器未配置允许前端页面直接跨域请求,浏览器会拦截这类跨域响应,以此保护用户安全。

解决方法

方案1:通过后端代理请求(生产环境推荐)

前端无法直接绕过浏览器的同源限制,最稳妥的方式是搭建一个后端服务,由后端代为调用Clash Royale API,前端再请求自己的后端接口。

示例:Node.js(Express)后端代码

const express = require('express');
const fetch = require('node-fetch');
const app = express();
const PORT = 3000;

// 替换成你的Clash Royale API Token
const CLASH_ROYALE_TOKEN = 'your_token_here';

app.get('/api/clashroyale/player/:tag', async (req, res) => {
  try {
    const playerTag = req.params.tag;
    const response = await fetch(`https://api.clashroyale.com/v1/players/%23${playerTag}`, {
      headers: {
        'Authorization': `Bearer ${CLASH_ROYALE_TOKEN}`
      }
    });

    if (!response.ok) {
      throw new Error(`API请求失败,状态码:${response.status}`);
    }

    const data = await response.json();
    res.json(data);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

app.listen(PORT, () => {
  console.log(`代理服务运行在 http://localhost:${PORT}`);
});

修改后的前端代码

function getClashRoyalePlayerInfo() {
  // 请求自己的后端代理接口,替换成你的后端地址
  fetch('http://localhost:3000/api/clashroyale/player/R09228V')
    .then((response) => {
      if (!response.ok) {
        throw new Error(`HTTP错误!状态码:${response.status}`);
      }
      return response.json();
    })
    .then((data) => {
      console.log(data); // 会返回你期望的玩家数据结构
    })
    .catch((error) => {
      console.error('错误:', error);
    });
}

getClashRoyalePlayerInfo();

方案2:本地开发临时绕过CORS(仅调试用)

如果只是本地开发调试,可以使用浏览器插件临时关闭同源限制,比如Chrome的「CORS Unblock」、Firefox的「CORS Everywhere」。

注意:此方法仅适合开发调试,绝对不能用于生产环境,会带来安全风险。

代码优化提示

  1. 原代码中GET请求无需设置Content-Type头,可删除该配置,减少不必要的请求头。
  2. 确保你的API Token正确且具备访问玩家信息的权限,可前往Clash Royale开发者后台核实。

内容的提问来源于stack exchange,提问作者NipulM

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 03:57:33