我在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时,它返回了403s:

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,可以尝试添加值为port443选项。

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();

关于node.js - 将HTTP请求从cURL转换为Node http.request,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22021995/

10-16 20:32