modernserf
modernserf

Reputation: 300

Translating http requests from cURL to Node http.request

I'm having some trouble with basic auth in Node.

Here's how I can do it via cURL as child process:

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

But it's returning 403s when I try https.request:

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

req.end();

And I get the same results with request:

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

Any ideas what I'm doing wrong here?

Upvotes: 2

Views: 1446

Answers (2)

modernserf
modernserf

Reputation: 300

The server was expecting a User-Agent.

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

Does the job.

Upvotes: 1

palanik
palanik

Reputation: 3669

Since it's https, could try adding port option with value 443.

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

req.end();

Or with auth option instead of header. Ref: 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();

Upvotes: 1

Related Questions