【问题标题】:How to download GitHub release asset from private repo using node如何使用节点从私有仓库下载 GitHub 发布资产
【发布时间】:2017-03-27 15:32:15
【问题描述】:

我想使用 node.js request 模块从私人仓库下载发布资产。它适用于以下cURL 命令:

curl -O -J -L \
     -H "Accept: application/octet-stream" \
https://__TOKEN__:@api.github.com/repos/__USER__/__REPO__/releases/assets/__ASSET_ID__

但是当我尝试使用 request 模块时它失败了:

var request = require('request');

var headers = {
    'Accept': 'application/octet-stream'
};
var API_URL = "https://__TOKEN__:@api.github.com/repos/__USER__/__REPO__"
var ASSET_ID = __ASSET_ID__

var options = {
    url: `${API_URL}/releases/assets/${ASSET_ID}`,
    headers: headers,
};


function callback(error, response, body) {
    if (error) {
        console.error(error);
    }
    console.log(response.statusCode)
    if (!error && response.statusCode == 200) {
        console.log(body);
    }

    console.log(options.url);
}
var req = request(options, callback);
console.log(req.headers)

我仔细检查了使用 node 时生成的 URL 是否与我使用 cURL 时的 URL 相同。

我在响应中收到403 statusCode。我不明白为什么。

更新: 在查看实际发送的标头时,我发现它使用了

{ Accept: 'application/octet-stream',
  host: 'api.github.com',
  authorization: 'Basic __DIFFERENT_TOKEN__' }

我不明白为什么要更改令牌。

一些参考:https://gist.github.com/maxim/6e15aa45ba010ab030c4

【问题讨论】:

  • 您尝试使用 cURL 尝试使用 node 下载但失败了吗?是否有可能资源被移动或您的令牌不再有效?
  • 我做到了。这不是令牌问题,资源没有移动。
  • 你检查过 403 响应的正文吗?它可能会为正在发生的事情提供线索。另外,你为什么使用followAllRedirects?根据the docs,这用于遵循非 GET 响应,但您使用的是 GET。在您的情况下,您只需要followRedirect,默认情况下已经是true
  • 你是对的。我更新了问题。我还添加了关于实际发送的标头的注释。奇怪
  • 讽刺:request 页面上的示例使用 GitHub 并显示如何设置用户代理:github.com/request/request#custom-http-headers

标签: node.js curl github


【解决方案1】:

GitHub API 需要用户代理 (https://github.com/request/request#custom-http-headers)

将编码设置为 null 也很重要,以便在正文中有缓冲区而不是字符串 (Getting binary content in Node.js using request)

代码的工作版本如下:

var request = require('request');

var headers = {
    'Accept': 'application/octet-stream',
    'User-Agent': 'request module',
};
var API_URL = "https://__TOKEN__:@api.github.com/repos/__USER__/__REPO__"
var ASSET_ID = __ASSET_ID__

var options = {
    url: `${API_URL}/releases/assets/${ASSET_ID}`,
    headers: headers,
    encoding: null // we want a buffer and not a string
};


function callback(error, response, body) {
    if (error) {
        console.error(error);
    }
    console.log(response.statusCode)
    if (!error && response.statusCode == 200) {
        console.log(body);
    }

    console.log(options.url);
}
var req = request(options, callback);
console.log(req.headers)

感谢 Marko Grešak。

【讨论】:

  • 如果您回答了自己的问题,请接受。
猜你喜欢
  • 2017-06-24
  • 2021-08-01
  • 1970-01-01
  • 2022-11-04
  • 1970-01-01
  • 2013-12-22
  • 2015-08-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多