【问题标题】:proxy authentication in node.js with module requestnode.js 中的代理身份验证与模块请求
【发布时间】:2014-05-10 19:29:18
【问题描述】:

我正在尝试在我的 node.js 应用程序中使用模块 request,我需要使用身份验证配置代理设置。

我的设置是这样的:

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

发出请求时如何设置代理配置?有人可以给我一个例子吗?谢谢

【问题讨论】:

    标签: node.js proxy httpclient proxy-authentication


    【解决方案1】:

    这里是一个如何配置的例子(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) {
      ...
    })
    

    【讨论】:

    • 您的回答帮助我到达了我需要的地方。 +1
    • 执行此操作时没有响应。你知道有什么特别的原因吗?
    • 维克多,谢谢!
    【解决方案2】:

    接受的答案没有错,但我想传递一个替代方案,以满足我发现的一些不同的需求。

    特别是我的项目有一系列代理可供选择,而不仅仅是一个。所以每次发出请求,重新设置 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
    });
    

    希望这对遇到同样问题的人有所帮助。干杯。

    【讨论】:

    • reqProxy 是另一个包吗?
    • @sidonaldson 不,reqProxy 只是我为提供代理字符串而编写的一个模块。
    • 奇怪。 request.defaults 对我不起作用。相反,这个解决方案奏效了。
    【解决方案3】:

    代理参数接受一个带有代理服务器 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 } 
        })
    });
    

    【讨论】:

    • http: 放入proxy 是我的关键。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-02
    • 2012-11-10
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 2020-09-04
    • 1970-01-01
    相关资源
    最近更新 更多