HTTP Client based on NodeJS: How to authenticate a

2020-02-26 03:15发布

This is the code I have to make a simple GET request:

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

But that path "/restricted" requires a simple basic HTTP authentication. How do I add the credentials to authenticate? I couldn't find anything related to basic http authentication in NodeJS' manual. Thanks in advance.

4条回答
forever°为你锁心
2楼-- · 2020-02-26 03:39

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
});
查看更多
相关推荐>>
3楼-- · 2020-02-26 03:52

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)

查看更多
走好不送
4楼-- · 2020-02-26 03:52

Here is some information on basic HTTP authentication.

查看更多
在下西门庆
5楼-- · 2020-02-26 03:59

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')
   }         
};
查看更多
登录 后发表回答