带有模块请求的 node.js 中的代理身份验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23585371/
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
proxy authentication in node.js with module request
提问by Victor
I'm trying to use the module requestin my node.js app, and I need to configure proxy settings with authentication.
我正在尝试在我的 node.js 应用程序中使用模块请求,我需要使用身份验证配置代理设置。
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
我如何在发出请求时设置我的代理配置?有人可以给我一个例子吗?谢谢
回答by Victor
Here is an example of how to configure (https://github.com/mikeal/request/issues/894):
以下是如何配置的示例(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) {
...
})
回答by 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.
特别是我的项目有一系列代理可供选择,而不仅仅是一个。所以每次我提出请求时,重新设置 request.defaults 对象没有多大意义。相反,您可以直接将其传递给请求选项。
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]
reqProxy.getProxy()返回一个字符串,相当于 [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.
希望这可以帮助遇到同样问题的人。干杯。
回答by svnm
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
代理参数采用带有代理服务器 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 }
})
});

