具有模块请求的node.js中的代理authentication

我试图在我的node.js应用程序中使用模块请求 ,我需要configuration代理设置与身份validation。

我的设置是这样的:

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

当我提出请求时,如何设置我的代理configuration? 有人能给我一个例子吗? 谢谢

这里是一个如何configuration( 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) { ... }) 

接受的答案是没有错的,但我想通过一个替代scheme来满足我发现的不同需求。

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

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

reqProxy.getProxy()返回一个等同于[protocol]://[username]:[pass]@[address]:[port]的string[protocol]://[username]:[pass]@[address]:[port]

然后提出请求

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

希望这可以帮助那些正在同样问题的人。 干杯。

代理参数需要一个string与您的代理服务器的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 } }) });