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

时间:2010-10-11 09:52:48

标签: node.js basic-authentication

根据标题,我该怎么做?

这是我的代码:

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

9 个答案:

答案 0 :(得分:251)

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

在这种情况下,它包含身份验证类型Basic以及在Base64中编码的username:password组合:

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

答案 1 :(得分:55)

来自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();

答案 2 :(得分:12)

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

使用request库:

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

我也写了一点blogpost

答案 3 :(得分:11)

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

答案 4 :(得分:8)

为什么值得我在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);
});

答案 5 :(得分: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);
    });
});

答案 6 :(得分:2)

我最近遇到过这个。 要设置的代理授权授权标头中的哪一个取决于客户端正在与之通信的服务器。 如果是Web服务器,则需要设置授权,如果是代理,则必须设置代理授权标头

答案 7 :(得分:0)

经过大量研究后,此代码适用于我的案例。您需要安装request npm package

var url = "http://api.example.com/api/v1/?param1=1&param2=2";
var auth = "Basic " + new Buffer(username + ":" + password).toString("base64");
exports.checkApi = function (req, res) {
    // do the GET request
    request.get({
        url: url,
        headers: {
            "Authorization": auth
        }
    }, function (error, response, body) {
        if(error)
       { console.error("Error while communication with api and ERROR is :  " + error);
       res.send(error);
    }
        console.log('body : ', body);
        res.send(body);      

    });    
}

答案 8 :(得分:0)

对于那些不使用 DNS 并需要更多深度的人(您也可以使用 request 代替 get,只需将 get 替换为 request,如下所示:{{1} }):

http.request({ ... })