Pregunta

I'm trying to use the module request in my node.js app, and I need to configure proxy settings with authentication.

My settings are something like this:

proxy:{
    host:"proxy.foo.com",
    port:8080,
    user:"proxyuser",
    password:"123"
}

How can i set my proxy configuration when i make a request? Could someone give me an example? thanks

¿Fue útil?

Solución

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) {
  ...
})

Otros consejos

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 } 
    })
});
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top