【问题标题】:HTTP Client based on NodeJS: How to authenticate a request?基于 NodeJS 的 HTTP 客户端:如何对请求进行身份验证?
【发布时间】:2011-10-18 14:22:28
【问题描述】:

这是我必须发出一个简单的 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 身份验证。如何添加凭据以进行身份​​验证?我在NodeJS' manual 中找不到与基本http 身份验证相关的任何内容。 提前致谢。

【问题讨论】:

    标签: http authentication node.js restful-authentication basic-authentication


    【解决方案1】:

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

    【讨论】:

    • 我知道它是如何工作的,但我似乎无法理解如何使用 NodeJS 的 http 库来做到这一点......我应该将带有我的用户名和密码的 base64 编码字符串放在哪里?
    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

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

      var options = {
          host: 'localhost',
          port: 8000,
          path: '/restricted',
          auth: username + ':' + password
      };
      
      request = http.get(options, function(res){
          //...
      });
      

      (注意:在 v0.10.3 上测试)

      【讨论】:

        【解决方案4】:

        我建议为此使用 request 模块,它支持广泛的功能,包括 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
        });
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-11-11
          • 1970-01-01
          • 1970-01-01
          • 2011-08-29
          • 2018-07-03
          • 1970-01-01
          • 2011-04-13
          • 1970-01-01
          相关资源
          最近更新 更多