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?
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With