使用 create-react-app 时 Github API 返回 CORS 错误

发布于 2025-01-10 08:31:16 字数 1053 浏览 0 评论 0原文

我正在尝试下载特定私有存储库的最新版本。我可以使用此 GET 请求收集信息:

const handleDownload = async () => {
    const token = "{Very secret token not for StackOverflow}";
    const owner = {company};
    
    const response = await fetch(
      `https://api.github.com/repos/${owner}/${repo}/releases/latest`,
      {
        //mode: 'no-cors',
        headers: {
          Authorization: 'Bearer ' + token,
        },
      }
    );

    const log = await response.json();
    console.log(log);
}

此调用返回一些数据,包括“zipball_url”属性,我认为我的下载来自该属性。但是,如果我尝试向此 URL(包括我的令牌)发出请求,我会收到令人讨厌的 CORS 错误:

访问'https://codeload.github.com/{company}/{reponame}/legacy.zip/refs/tags/1.1.7?token={secret token}'(重定向自'https来自来源“http://localhost:3000”的://api.github.com/repos/{company}/{reponame}/zipball/1.1.7') 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。如果不透明响应满足您的需求,请将请求模式设置为“no-cors”以在禁用 CORS 的情况下获取资源。

Github API 文档对我帮助不大。有人可以解释一下如何解决这个问题吗?

I am trying to download the latest release of a specific private repository. I am able to gather information by using this GET request:

const handleDownload = async () => {
    const token = "{Very secret token not for StackOverflow}";
    const owner = {company};
    
    const response = await fetch(
      `https://api.github.com/repos/${owner}/${repo}/releases/latest`,
      {
        //mode: 'no-cors',
        headers: {
          Authorization: 'Bearer ' + token,
        },
      }
    );

    const log = await response.json();
    console.log(log);
}

This call returns some data, including the 'zipball_url' property, where i think my download comes from. However, if i try to make a request to this URL (including my token), i am getting a nasty CORS error:

Access to fetch at 'https://codeload.github.com/{company}/{reponame}/legacy.zip/refs/tags/1.1.7?token={secret token}' (redirected from 'https://api.github.com/repos/{company}/{reponame}/zipball/1.1.7') from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: 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.

The Github API Docs are not helping me very much. Can someone explain me how to fix this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

七禾 2025-01-17 08:31:16

zipball_url 只是重定向到 codeload.github.com 子域,Github 不允许公共 CORS 访问该子域。

如果您希望用户下载文件,只需直接在 元素中使用 zipball_url 即可。

const [ zipUrl, setZipUrl ] = useState(null)

const downloadRef = useRef(null)

const getLatestRelease = async () => {
  // this is greatly simplified with no error handling for brevity  
  const res = await fetch(yourGithubUrl)
  return (await res.json()).zipball_url
}

useEffect(() => {
  getLatestRelease().then(setZipUrl)
}, [])

useEffect(() => {
  // trigger download
  if (zipUrl) {
    downloadRef.current.click()
  }
}, [ zipUrl ])

return zipUrl && (
  <a
    download
    ref={downloadRef}
    href={zipUrl}
  >
    Download
  </a>
)

另一种选择是使用 window.open (zipball_url) 但这将打开一个新选项卡。

The zipball_url simply redirects to the codeload.github.com sub-domain and Github doesn't allow public CORS access to that.

If you're wanting the user to download the file, just use the zipball_url directly in a <a download> element

const [ zipUrl, setZipUrl ] = useState(null)

const downloadRef = useRef(null)

const getLatestRelease = async () => {
  // this is greatly simplified with no error handling for brevity  
  const res = await fetch(yourGithubUrl)
  return (await res.json()).zipball_url
}

useEffect(() => {
  getLatestRelease().then(setZipUrl)
}, [])

useEffect(() => {
  // trigger download
  if (zipUrl) {
    downloadRef.current.click()
  }
}, [ zipUrl ])

return zipUrl && (
  <a
    download
    ref={downloadRef}
    href={zipUrl}
  >
    Download
  </a>
)

Another option is to use window.open(zipball_url) but that will open a new tab.

北渚 2025-01-17 08:31:16

我也遇到了同样的错误:
{ "message": "Not Found", "documentation_url": "https://docs.github.com/rest/reference/repos#download-a-repository-archive" }

当我在下面注册时它得到了解决url,已解决:

要登录,请使用 Web 浏览器打开页面 https://microsoft.com/devicelogin< /a> 和输入代码 XXXXXXXXXX 进行身份验证。

I also got the same error:
{ "message": "Not Found", "documentation_url": "https://docs.github.com/rest/reference/repos#download-a-repository-archive" }

and it got resolved when i register in the below url, it got resolved:

To sign in, use a web browser to open the page https://microsoft.com/devicelogin and enter the code XXXXXXXXXXX to authenticate.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文