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

JavaScript调用GitHub API出现CORS错误,如何解决?

解决GitHub API的CORS错误问题

问题原因

  1. 无效的请求头设置:Access-Control-Allow-Origin是服务器返回给浏览器的响应头,用于授权跨域请求,前端在请求中添加这个头完全没用,反而会触发浏览器的预检OPTIONS请求,引发CORS报错。
  2. 同步请求的限制:代码里使用了同步XMLHttpRequest(open第三个参数为false),现代浏览器对主线程中的同步请求有严格限制,这也会加重跨域相关问题。

修正后的代码

方案1:修复XMLHttpRequest写法

<script>
function testingAPI(){
  const theUrl = "https://api.github.com/users/juliolimacostavalladares";
  const xmlHttp = new XMLHttpRequest();
  xmlHttp.onload = function() {
    alert(xmlHttp.responseText);
  };
  xmlHttp.onerror = function() {
    alert(xmlHttp.status);
  };
  // 改为异步请求(第三个参数默认是true,可省略)
  xmlHttp.open("GET", theUrl); 
  xmlHttp.setRequestHeader("Accept","application/json");
  // 移除无效的Access-Control-Allow-Origin请求头
  xmlHttp.send();
}
</script>

<body>
  <button onclick="testingAPI()"> send request </button>
</body>

方案2:使用更简洁的Fetch API

<script>
async function testingAPI(){
  try {
    const response = await fetch("https://api.github.com/users/juliolimacostavalladares", {
      headers: {
        "Accept": "application/json"
      }
    });
    const data = await response.json();
    alert(JSON.stringify(data));
  } catch (err) {
    alert(err.message);
  }
}
</script>

<body>
  <button onclick="testingAPI()"> send request </button>
</body>

额外说明

GitHub公开API本身支持CORS,只要请求符合规范(不设置无效请求头、使用异步请求)就能正常访问。如果后续需要调用需认证的GitHub API,只需在请求头中添加Authorization: token 你的GitHub令牌即可,无需额外处理CORS。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 04:49:57