基于NodeJS的HTTP客户端:如何对请求进行身份验证?

基于NodeJS的HTTP客户端:如何对请求进行身份验证?,http,authentication,node.js,restful-authentication,basic-authentication,Http,Authentication,Node.js,Restful Authentication,Basic Authentication,这是我必须发出一个简单GET请求的代码: 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',

这是我必须发出一个简单GET请求的代码:

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);
    });
});
但该路径“/restricted”需要一个简单的基本HTTP身份验证。如何添加凭据以进行身份验证?我在中找不到任何与基本http身份验证相关的内容。
提前感谢。

是有关基本HTTP身份验证的一些信息。

您需要将授权添加到选项中,例如使用base64编码的标头。比如:

var options = {
    host: 'localhost',
    port: 8000,
    path: '/restricted',
    headers: {
     'Authorization': 'Basic ' + new Buffer(uname + ':' + pword).toString('base64')
   }         
};
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
});

在较新的版本中,您也可以只在选项中添加auth参数(格式为username:password,无编码):

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

request = http.get(options, function(res){
    //...
});
(注意:在v0.10.3上测试)

我建议使用该模块,它支持广泛的功能,包括HTTP基本身份验证

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

我知道它是如何工作的,但我似乎不明白如何使用NodeJS的http库。。。我应该将带有用户名和密码的base64编码字符串放在哪里?