【问题标题】:Translating http requests from cURL to Node http.request将 http 请求从 cURL 转换为节点 http.request
【发布时间】:2014-02-25 17:43:23
【问题描述】:

我在 Node 中的基本身份验证遇到了一些问题。

以下是我可以通过 cURL 作为子进程的方法:

var auth = 'Basic ' + new Buffer(username + ":" + password).toString('base64');
var url =  'https://' + hostname + path;

var curlstr = "curl #{url} -H 'Authorization: #{auth}'"
  .replace('#{url}', url)
  .replace('#{auth}', auth);

require('child_process').exec(curlstr, function (err, stdout, stderr){
  console.log(stdout);
});

但是当我尝试 https.request 时它返回 403:

var req = https.request({
  hostname: hostname,
  path: path,
  headers: {'Authorization': auth}
}, function (res){
  console.log(res.statusCode);
});

req.end();

我得到与request 相同的结果:

request({
  method: 'GET',
  url: url,
  auth: {
    username: username,
    password: password
  }
}, function (err,res,body){
  console.log(res.statusCode);
});

有什么想法我在这里做错了吗?

【问题讨论】:

  • 我怀疑你的 HTTPS 服务器发生了错误,你能分享那个代码吗?
  • 如果可以的话,在 HTTPS 服务器上记录请求标头会很有帮助。通过这种方式,您可以检查您是否正在发送您认为您正在发送的身份验证信息。另请查看sendImmediately parameterrequest
  • 我无法控制与我通信的服务器,但我会尝试将请求发送到测试服务器,以便查看请求有何不同。

标签: node.js curl


【解决方案1】:

由于是https,可以尝试添加port选项,值为443

var req = https.request({
  hostname: hostname,
  port: 443,
  path: path,
  headers: {'Authorization': auth}
}, function (res){
  console.log(res.statusCode);
});

req.end();

或者使用auth 选项而不是header。 参考:http://nodejs.org/api/http.html#http_http_request_options_callback

var req = https.request({
      hostname: hostname,
      port: 443,
      path: path,
      auth: username + ':' + password
    }, function (res){
      console.log(res.statusCode);
    });

    req.end();

【讨论】:

    【解决方案2】:

    服务器期待一个用户代理。

    request({
      method: 'GET',
      url: url,
      headers: {'User-Agent': 'curl'},
      auth: {
        username: username,
        password: password
      }
    }, function (err,res,body){
      console.log(body);
    });
    

    完成这项工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多