How to use http.client in Node.js if there is basic authorization
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);
});
});
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);
From Node.js http.request API Docs you could use something similar to
var http = require('http');
var request = http.request({'hostname': 'www.example.com',
'auth': 'user:password'
},
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);
});
});
request.end();
var username = "Ali";
var password = "123";
var auth = "Basic " + new Buffer(username + ":" + password).toString("base64");
var request = require('request');
var url = "http://localhost:5647/contact/session/";
request.get( {
url : url,
headers : {
"Authorization" : auth
}
}, function(error, response, body) {
console.log('body : ', body);
} );