How to use http.client in Node.js if there is basic authorization

de_3 picture de_3 · Oct 11, 2010 · Viewed 154.5k times · Source

As per title, how do I do that?

Here is my code:

var http = require('http');

// to access this url I need to put basic auth.
var client = http.createClient(80, 'www.example.com');

var request = client.request('GET', '/', {
    'host': 'www.example.com'
});
request.end();
request.on('response', function (response) {
  console.log('STATUS: ' + response.statusCode);
  console.log('HEADERS: ' + JSON.stringify(response.headers));
  response.setEncoding('utf8');
  response.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
  });
});

Answer

Ivo Wetzel picture Ivo Wetzel · Oct 11, 2010

You have to set the Authorization field in the header.

It contains the authentication type Basic in this case and the username:password combination which gets encoded in Base64:

var username = 'Test';
var password = '123';
var auth = 'Basic ' + Buffer.from(username + ':' + password).toString('base64');
// new Buffer() is deprecated from v6

// auth is: 'Basic VGVzdDoxMjM='

var header = {'Host': 'www.example.com', 'Authorization': auth};
var request = client.request('GET', '/', header);