【问题标题】:403 error from Github.js getSha for files above ~1MB in size来自 Github.js getSha 的 403 错误,用于大小超过 ~1MB 的文件
【发布时间】:2018-05-30 16:45:04
【问题描述】:

当我尝试使用Github.js 从大于~1MB 的文件中获取Sha(以及随后的getBlob)时,我收到了403 错误。文件大小有限制吗?代码如下:

var gh = new GitHub({
    username: username,
    password: password
});

// get the repo from github
var repo = gh.getRepo('some-username','name-of-repo');

// get promise
repo.getSha('some-branch', 'some-file.json').then(function(result){

  // pass the sha onto getBlob
  return repo.getBlob(result.data.sha);

}).then(function(result){

  do_something_with_blob(result.data);

});

GitHub API 表示它支持最大 100MB 大小的 blob,我在 Github.js docs 中找不到任何关于文件大小限制的信息。此外,这些文件来自私人 Github 存储库。

【问题讨论】:

    标签: javascript github github-api http-status-code-403 github.js


    【解决方案1】:

    它会引发403 Forbidden 错误,因为它使用Github GET contents API,它会为文件提供不超过 1Mo 的结果。例如以下将抛出 403 :

    https://api.github.com/repos/bertrandmartel/w230st-osx/contents/CLOVER/tools/Shell64.efi?ref=master

    使用this method和GET tree API,你可以在不下载整个文件的情况下获取文件sha,然后使用repo.getBlob(对于不超过100Mo的文件使用Get blob API)。

    以下示例将使用 GET trees api 获取指定文件(对于超过 1Mo 的文件)的父文件夹的树,按名称过滤特定文件,然后请求 blob 数据:

    const accessToken = 'YOUR_ACCESS_TOKEN';
    
    const gh = new GitHub({
      token: accessToken
    });
    
    const username = 'bertrandmartel';
    const repoName = 'w230st-osx';
    const branchName = 'master';
    const filePath = 'CLOVER/tools/Shell64.efi'
    
    var fileName = filePath.split(/(\\|\/)/g).pop();
    var fileParent = filePath.substr(0, filePath.lastIndexOf("/"));
    
    var repo = gh.getRepo(username, repoName);
    
    fetch('https://api.github.com/repos/' +
      username + '/' +
      repoName + '/git/trees/' +
      encodeURI(branchName + ':' + fileParent), {
        headers: {
          "Authorization": "token " + accessToken
        }
      }).then(function(response) {
      return response.json();
    }).then(function(content) {
      var file = content.tree.filter(entry => entry.path === fileName);
    
      if (file.length > 0) {
        console.log("get blob for sha " + file[0].sha);
        //now get the blob
        repo.getBlob(file[0].sha).then(function(response) {
          console.log("response size : " + response.data.length);
        });
      } else {
        console.log("file " + fileName + " not found");
      }
    });
    

    【讨论】:

    • 感谢它适用于公共存储库,但我似乎无法获取私有存储库的树(使用 fetch),其中出现 404 错误。我猜这是因为 fetch 没有传递任何身份验证令牌。有没有办法使用 Fetch 传递令牌或使用已经拥有令牌的 gh 对象中的方法获取树?
    • @NickFernandez 我已经更新了答案,在获取选项中添加了授权标头
    • @maugch 它在哪里?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多