[英]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.