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

Viewed 186319

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

For those not using DNS and needs more depth (you can also use request instead of get by simply replacing get with request like so: http.request({ ... })):

http.get({ 
    host: '127.0.0.1',
    port: 443,
    path: '/books?author=spongebob',
    auth: 'user:p@ssword#'
 }, resp => {
    let data;

    resp.on('data', chunk => {
        data += chunk;
    });

    resp.on('end', () => console.log(data));
}).on('error', err => console.log(err));
Related