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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3905126/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 13:42:12  来源:igfitidea点击:

How to use http.client in Node.js if there is basic authorization

node.jsbasic-authentication

提问by de_3

As per title, how do I do that?

根据标题,我该怎么做?

Here is my code:

这是我的代码:

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

回答by Ivo Wetzel

You have to set the Authorizationfield in the header.

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

It contains the authentication type Basicin this case and the username:passwordcombination which gets encoded in Base64:

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

回答by Sujay

From Node.js http.request API Docsyou could use something similar to

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

回答by Hamidreza Sadegh

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

回答by Husky

An easier solution is to use the user:pass@host format directly in the URL.

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

Using the requestlibrary:

使用请求库:

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

I've written a little blogpostabout this as well.

我也写了一篇关于这个的小博文

回答by vrtis

for what it's worth I'm using node.js 0.6.7 on OSX and I couldn't get 'Authorization':auth to work with our proxy, it needed to be set to 'Proxy-Authorization':auth my test code is:

对于我在 OSX 上使用 node.js 0.6.7 的价值,我无法获得 'Authorization':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);
});

回答by Manish Kumar

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

回答by sdqali

I came across this recently. Which among Proxy-Authorizationand Authorizationheaders to set depends on the server the client is talking to. If it is a Webserver, you need to set Authorizationand if it a proxy, you have to set the Proxy-Authorizationheader

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

回答by Nimish goel

This code works in my case, after a lot of research. You will require to install the request npm package.

经过大量研究,此代码适用于我的情况。您将需要安装请求 npm 包

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

    });    
}