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

十年热恋 提交于 2019-11-30 07:57:17

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')
   }         
};

In newer version you can also just add auth parameter (in format username:password, no encoding) to your options:

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

request = http.get(options, function(res){
    //...
});

(NOTE: tested on v0.10.3)

I suggest to use request module for that, it support wide range functionalities including HTTP Basic Authentication.

var username = 'username',
    password = 'password',
    url = 'http://' + username + ':' + password + '@some.server.com';

request({url: url}, function (error, response, body) {
   // Do more stuff with 'body' here
});

Here is some information on basic HTTP authentication.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!