如果有基本授权,如何在Node.js中使用http.client

de_*_*e_3 103 basic-authentication node.js

按照标题,我该怎么做?

这是我的代码:

var http = require('http');

// to access this url I need to put basic auth.
var client = http.createClient(80, 'www.example.com');

var request = client.request('GET', '/', {
    'host': 'www.example.com'
});
request.end();
request.on('response', function (response) {
  console.log('STATUS: ' + response.statusCode);
  console.log('HEADERS: ' + JSON.stringify(response.headers));
  response.setEncoding('utf8');
  response.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
  });
});
Run Code Online (Sandbox Code Playgroud)

Ivo*_*zel 265

您必须Authorization在标题中设置字段.

它包含Basic本例中的身份验证类型以及username:password在Base64中编码的组合:

var username = 'Test';
var password = '123';
var auth = 'Basic ' + Buffer.from(username + ':' + password).toString('base64');
// new Buffer() is deprecated from v6

// auth is: 'Basic VGVzdDoxMjM='

var header = {'Host': 'www.example.com', 'Authorization': auth};
var request = client.request('GET', '/', header);
Run Code Online (Sandbox Code Playgroud)

  • 这就是整个事情的运作方式.服务器期望数据在Base64中编码. (3认同)
  • 这个例子中的"客户"是什么? (3认同)

Suj*_*jay 59

Node.js http.request API Docs 你可以使用类似的东西

var http = require('http');

var request = http.request({'hostname': 'www.example.com',
                            'auth': 'user:password'
                           }, 
                           function (response) {
                             console.log('STATUS: ' + response.statusCode);
                             console.log('HEADERS: ' + JSON.stringify(response.headers));
                             response.setEncoding('utf8');
                             response.on('data', function (chunk) {
                               console.log('BODY: ' + chunk);
                             });
                           });
request.end();
Run Code Online (Sandbox Code Playgroud)

  • 这是现代的答案. (8认同)
  • 你需要做"用户:密码"或"基本用户:密码"吗? (2认同)
  • @kayvar你不需要用Basic作为前缀. (2认同)

Hus*_*sky 13

更简单的解决方案是使用user:直接在URL中传递@host格式.

使用请求库:

var request = require('request'),
    username = "john",
    password = "1234",
    url = "http://" + username + ":" + password + "@www.example.com";

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

我也写了一篇关于此的博文.

  • 这不是理想的建议:在客户端或服务器端的任何URL记录都可能暴露密码值 - 这是一个众所周知的安全攻击向量.我强烈建议没有人这样做.标头值更好,而不使用基本身份验证 - 支持摘要式身份验证或OAuth 1.0a(例如)更好.RFC 3986中的URI中也不推荐使用这种形式的标识. (17认同)

Ham*_*egh 13

var username = "Ali";
var password = "123";
var auth = "Basic " + new Buffer(username + ":" + password).toString("base64");
var request = require('request');
var url = "http://localhost:5647/contact/session/";

request.get( {
    url : url,
    headers : {
        "Authorization" : auth
    }
  }, function(error, response, body) {
      console.log('body : ', body);
  } );
Run Code Online (Sandbox Code Playgroud)


小智 10

为什么值得我在OSX上使用node.js 0.6.7并且我无法获得'授权':auth使用我们的代理,它需要设置为'Proxy-Authorization':auth我的测试代码是:

var http = require("http");
var auth = 'Basic ' + new Buffer("username:password").toString('base64');
var options = {
    host: 'proxyserver',
    port: 80,
    method:"GET",
    path: 'http://www.google.com',
    headers:{
        "Proxy-Authorization": auth,
        Host: "www.google.com"
    } 
};
http.get(options, function(res) {
    console.log(res);
    res.pipe(process.stdout);
});
Run Code Online (Sandbox Code Playgroud)

  • 对于未来读者的启发:这是因为您使用代理服务器进行身份验证,而不是使用目标网络服务器(谷歌)进行身份验证.如果您需要使用目标服务器进行身份验证,则Authorization标头将是您要使用的标头. (3认同)

Man*_*mar 6

var http = require("http");
var url = "http://api.example.com/api/v1/?param1=1&param2=2";

var options = {
    host: "http://api.example.com",
    port: 80,
    method: "GET",
    path: url,//I don't know for some reason i have to use full url as a path
    auth: username + ':' + password
};

http.get(options, function(rs) {
    var result = "";
    rs.on('data', function(data) {
        result += data;
    });
    rs.on('end', function() {
        console.log(result);
    });
});
Run Code Online (Sandbox Code Playgroud)