我正在尝试在我的 node.js 应用程序中使用模块请求,并且我需要使用身份验证配置代理设置。
我的设置是这样的:
proxy:{
host:"proxy.foo.com",
port:8080,
user:"proxyuser",
password:"123"
}
发出请求时如何设置代理配置?有人可以给我一个例子吗?谢谢
我正在尝试在我的 node.js 应用程序中使用模块请求,并且我需要使用身份验证配置代理设置。
我的设置是这样的:
proxy:{
host:"proxy.foo.com",
port:8080,
user:"proxyuser",
password:"123"
}
发出请求时如何设置代理配置?有人可以给我一个例子吗?谢谢
以下是如何配置的示例(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) {
...
})
接受的答案没有错,但我想通过一个替代方案来满足我发现的一些不同的需求。
特别是我的项目有一系列代理可供选择,而不仅仅是一个。所以每次发出请求,重新设置 request.defaults 对象并没有多大意义。相反,您可以直接将其传递给请求选项。
var reqOpts = {
url: reqUrl,
method: "GET",
headers: {"Cache-Control" : "no-cache"},
proxy: reqProxy.getProxy()};
reqProxy.getProxy()
返回一个字符串,相当于[protocol]://[username]:[pass]@[address]:[port]
然后提出请求
request(reqOpts, function(err, response, body){
//handle your business here
});
希望这对遇到同样问题的人有所帮助。干杯。
代理参数采用带有代理服务器 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 }
})
});