proxy authentication in node.js with module request

ε祈祈猫儿з 提交于 2019-12-02 17:09:21

Here is an example of how to configure (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) {
  ...
})
James LeClair

The accepted answer is not wrong, but I wanted to pass along an alternative that satisfied a bit of a different need that I found.

My project in particular has an array of proxies to choose from, not just one. So each time I make a request, it doesn't make much sense to re-set the request.defaults object. Instead, you can just pass it through directly to the request options.

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

reqProxy.getProxy() returns a string to the equivalent of [protocol]://[username]:[pass]@[address]:[port]

Then make the request

request(reqOpts, function(err, response, body){
    //handle your business here
});

Hope this helps someone who is coming along this with the same issue. Cheers.

the proxy paramater takes a string with the url for your proxy server, in my case the proxy server was at 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 } 
    })
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!