【发布时间】:2021-12-29 17:28:45
【问题描述】:
问题
我负责尝试从我公司组织的私有存储库中的文件中检索 json 数据。我是该组织的所有者,但在使用从我的 GitHub 帐户生成的个人访问令牌时不断收到 404 或 401 错误。
-
为什么我不能使用 OAuth
此节点应用程序将用作存储库中 GH Actions 的一部分,并且用户将无法在每次推送到存储库时登录以验证访问权限。因此,我为什么要寻找使用某种访问令牌的解决方案。
我尝试过的事情:
- 查看其他 StackOverflow 问题,所有这些问题要么不相关、不起作用、未回答或已过时。
- 我尝试启用访问令牌的所有权限。 (其余的都是在启用所有权限的情况下完成的)
- 在 raw.githubusercontent.com 和 api.github.com 之间切换,每次添加和删除
Accept标头的.raw部分。 - 使用带有和不带有
Accept标头的每个 URL。 - 在每个 URL 中使用
Authorization: "token TOKEN"和Authorization: "Bearer TOKEN"。 - 使用我自己帐户中的存储库,这与我生成的访问令牌非常有效。
我目前正在使用的代码
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}`);
});
有点“工作”但不是理想的解决方案
有效的是使用这个 URL:https://raw.githubusercontent.com/ORG_NAME/REPO_NAME/main/path/data.json?token=SOME_RANDOM_GENERATED_TOKEN,并在点击 repo 页面上的 Raw 按钮后添加生成的令牌。我显然不想将此令牌用于生产操作。
我怎样才能让它工作?这个时候还有可能吗?
【问题讨论】:
-
这是企业云还是服务器?您要访问的存储库是私有的还是内部的?您可以使用文档中的 curl 命令尝试相同的操作吗? docs.github.com/en/enterprise-cloud@latest/rest/reference/…(请注意,我指的是企业云文档)。这将有助于使您的复制器更小。
-
它当前是服务器,但正在移动到企业帐户。我不确定您所说的内部是什么意思,但它是直接在组织内部创建的私有存储库。我会查看那些文档。
-
如果它是服务器(即在本地托管),您将无法在主机 api.github.com 上查询它
标签: typescript http-headers github-actions access-token github-api