Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

curl with --user option in nodejs

Tags:

node.js

curl

I can grab a webpage in nodejs, but I need to authenticate myself first. In curl you can do this with curl --user user:password [url].

How can I achieve the same results in node?

like image 439
user2787904 Avatar asked Oct 10 '13 02:10

user2787904


1 Answers

You just need to add an authorization header to your HTTP request. The Authorization header should contain the username and password combined with a colon, which should then be Base64 encoded, then prepended with Basic and a single space.

var header = 'Basic ' + new Buffer(user + ':' + pass).toString('base64');

Here's a complete example involving a GET request.

var http = require('http');

var user = 'username';
var pass = 'password';

var auth = new Buffer(user + ':' + pass).toString('base64');
var options = {
  host: 'example.com',
  port: 80,
  path: '/path',
  headers: {
    'Authorization': 'Basic ' + auth
  }
};

http.get(options, function(res) {
  // response is here
});
like image 168
hexacyanide Avatar answered Oct 02 '22 21:10

hexacyanide