HTTP Client based on NodeJS: How to authenticate a request?

João Pinto Jerónimo picture João Pinto Jerónimo · Aug 2, 2011 · Viewed 24.6k times · Source

This is the code I have to make a simple GET request:

var options = {
    host: 'localhost',
    port: 8000,
    path: '/restricted'
};

request = http.get(options, function(res){
    var body = "";
    res.on('data', function(data) {
        body += data;
    });
    res.on('end', function() {
        console.log(body);
    })
    res.on('error', function(e) {
        console.log("Got error: " + e.message);
    });
});

But that path "/restricted" requires a simple basic HTTP authentication. How do I add the credentials to authenticate? I couldn't find anything related to basic http authentication in NodeJS' manual. Thanks in advance.

Answer

Marcus Granström picture Marcus Granström · Aug 2, 2011

You need to add the Authorization to the options like a header encoded with base64. Like:

var options = {
    host: 'localhost',
    port: 8000,
    path: '/restricted',
    headers: {
     'Authorization': 'Basic ' + new Buffer(uname + ':' + pword).toString('base64')
   }         
};