如何使用节点从私有仓库下载GitHub发布资源

问题描述:

我想使用node.js request 模块从私有存储库下载发行资产.使用以下 cURL 命令可以正常工作:

I would like to use node.js request module to download a release asset from a private repo. It works fine with the following cURL command:

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

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

but it fails when I try using the request module:

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相同.

I have double checked that the resulting URL when using node is the same as the one I use with cURL.

我在响应中收到一个 403 statusCode.我不明白为什么.

I receive a 403 statusCode in the response. I do not understand why.

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

UPDATE: While looking at the headers that are actually sent, I have found that the it uses

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

我不明白为什么更改令牌.

I do not understand why the token is changed.

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

GitHub API需要用户代理(

GitHub API requires a user agent (https://github.com/request/request#custom-http-headers)

同样重要的是,将编码设置为null以便在主体中具有缓冲区而不是字符串(

It is also important to set the encoding to null in order to have a buffer and not a string in the body (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)

感谢MarkoGrešak.

Thanks to Marko Grešak.