具有模块请求的node.js中的代理身份验证

Vic*_*tor 28 proxy httpclient proxy-authentication node.js

我正在尝试在我的node.js应用程序中使用模块请求,我需要使用身份验证配置代理设置.

我的设置是这样的:

proxy:{
    host:"proxy.foo.com",
    port:8080,
    user:"proxyuser",
    password:"123"
}
Run Code Online (Sandbox Code Playgroud)

如何在提出请求时设置我的代理配置?有人能举个例子吗?谢谢

Vic*_*tor 42

以下是如何配置的示例(https://github.com/mikeal/request/issues/894):

//...some stuff to get my proxy config (credentials, host and port)
var proxyUrl = "http://" + user + ":" + password + "@" + host + ":" + port;

var proxiedRequest = request.defaults({'proxy': proxyUrl});

proxiedRequest.get("http://foo.bar", function (err, resp, body) {
  ...
})
Run Code Online (Sandbox Code Playgroud)

  • 你的回答帮助我到达了我需要的地方.+1 (3认同)

Jam*_*air 19

接受的答案并没有错,但我想传递一种满足我发现的不同需求的替代方案.

我的项目特别有一系列代理可供选择,而不仅仅是一个.因此,每次发出请求时,重新设置request.defaults对象都没有多大意义.相反,您可以直接将其传递给请求选项.

var reqOpts = {
    url: reqUrl, 
    method: "GET", 
    headers: {"Cache-Control" : "no-cache"}, 
    proxy: reqProxy.getProxy()};
Run Code Online (Sandbox Code Playgroud)

reqProxy.getProxy() 返回一个等效的字符串 [protocol]://[username]:[pass]@[address]:[port]

然后提出请求

request(reqOpts, function(err, response, body){
    //handle your business here
});
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助那些带着同样问题的人.干杯.


svn*_*vnm 9

代理参数使用代理服务器的URL作为字符串,在我的情况下,代理服务器处于 http://127.0.0.1:8888

request({ 
    url: 'http://someurl/api',
    method: 'POST',
    proxy: 'http://127.0.0.1:8888',
    headers: {
        'Content-Length': '2170',
        'Cache-Control': 'max-age=0'
    },
    body: body
  }, function(error, response, body){
    if(error) {
        console.log(error);
    } else {
      console.log(response.statusCode, body);
    }

    res.json({ 
      data: { body: body } 
    })
});
Run Code Online (Sandbox Code Playgroud)