Hang with --user option in nodejs

I can capture a webpage in nodejs, but first I need to go through authentication. In curl, you can do this with curl --user user:password [url].

How can I achieve the same results in node?

+4
source share
1 answer

You just need to add the authorization header to your HTTP request. The header Authorizationmust contain a username and password, combined with a colon, which must then be encoded in Base64, and then added with a Basicsingle space.

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

Here is 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
});
+8
source

All Articles