我如何使用 GitHub REST API 通过我的个人访问令牌访问组织拥有的私有存储库中的文件数据?

How can I use the GitHub REST API to access a file's data in a private repository owned by an organization via my personal access token?

问题

我负责尝试从公司组织的私有存储库中的文件中检索 json 数据。我是该组织的所有者,但在使用从我的 GitHub 帐户生成的个人访问令牌时,总是收到 404401 错误。

我尝试过的事情:

我目前使用的代码

https
  .get(
    // "https://raw.githubusercontent.com/ORG_NAME/REPO_NAME/main/path/data.json", // results in 404 error
    "https://api.github.com/repos/ORG_NAME/REPO_NAME/contents/path/data.json", // results in 403 error
    {
      headers: {
        // request the v3 version of the api
        Accept: "application/vnd.github.v3.raw+json",
        "Content-Type": "application/json;charset=UTF-8",
        Authorization: `token ${process.env.GH_TOKEN}`,
      },
    },
    res => {
    const statusCode = res.statusCode;
    const contentType = res.headers["content-type"] || "";

    let error;
    if (statusCode !== 200) {
       error = new Error(
         "Request Failed.\n" +
           `Status Code: ${statusCode}: ${res.statusMessage}`
        );
    } else if (!/^application\/json/.test(contentType)) {
      error = new Error(
        "Invalid content-type.\n" +
          `Expected application/json but received ${contentType}`
      );
    }
    if (error) {
      console.log(error.message);
      // consume response data to free up memory
      res.resume();
      return;
    }

    res.setEncoding("utf8");
    let rawData = "";
    res.on("data", chunk => (rawData += chunk));
    res.on("end", () => {
      try {
        const parsedData = JSON.parse(rawData);
        console.log(parsedData);
      } catch (e) {
        if (e instanceof Error) console.log(e.message);
      }
    });
  })
.on("error", e => {
  console.log(`Got error: ${e.message}`);
});

Sort-of“有效”但不是理想的解决方案

使用这个 URL: https://raw.githubusercontent.com/ORG_NAME/REPO_NAME/main/path/data.json?token=SOME_RANDOM_GENERATED_TOKEN,在点击回购页面的 Raw 按钮后添加生成的令牌。我显然不想将此令牌用于生产操作。

我怎样才能让它工作?这个时候还有可能吗?

我尝试了以下请求,它有效。

GET 'https://raw.githubusercontent.com/ORG_NAME/REPO_NAME/main/README.md' \
 Authorization:'token <Personal Access Token>'

问题可能在请求 URL 中 - 看起来您在请求 URL 中包含了 /路径/,这不是必需的。您需要提供文件的实际路径,因此正确的 URL 将是

https://raw.githubusercontent.com/ORG_NAME/REPO_NAME/main/data.json