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