簡體   English   中英

使用 create-react-app 時 Github API 返回 CORS 錯誤

[英]Github API returns CORS error when using create-react-app

我正在嘗試下載特定私有存儲庫的最新版本。 我可以通過使用這個 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 文檔對我幫助不大。 有人可以解釋我如何解決這個問題嗎?

zipball_url只是重定向到codeload.github.com子域,Github 不允許公共 CORS 訪問它。

如果您希望用戶下載文件,只需在<a download>元素中直接使用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)但這將打開一個新選項卡。

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

當我在下面的 url 中注冊時它得到了解決,它得到了解決:

要登錄,請使用 Web 瀏覽器打開頁面https://microsoft.com/devicelogin並輸入代碼 XXXXXXXXXXX 進行身份驗證。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM