【问题标题】:How to get host name in http response in node.js?如何在 node.js 的 http 响应中获取主机名?
【发布时间】:2013-09-25 11:03:28
【问题描述】:

我正在使用 node.js 的 http 模块来发出请求。我在数据库中有一堆网址。我正在从数据库中获取这些 url 并在循环中发出请求。但是当响应到来时,我想获取该响应的主机名,因为我想根据该响应更新数据库中的某些内容。但是我没有得到我正在获得响应的站点,因此我无法更新该站点的记录。

代码是这样的:

for (site = 0; site < no_of_sites; site++) {
    options = {
        hostname: sites[site].name,
        port: 80,
        method: 'GET',
        headers: {
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; rv:11.0) Gecko/20100101 Firefox/11.0'
        }
    };

    var req = http.request(options, function (res) {
        console.log('HEADERS: ' + JSON.stringify(res.headers));
        if (res.statusCode == 200) {

            //Update record;
        }
    });
}

【问题讨论】:

    标签: javascript node.js http httpresponse


    【解决方案1】:

    我们可以在this对象中获取主机站点。

    console.log(this._header.match(/Host\:(.*)/g));
    

    【讨论】:

      【解决方案2】:

      选项一:使用res.req

      var req = http.request(options, function (res) {
        console.log(res.req._headers.host)
      });
      

      选项二:使用闭包

      for (site = 0; site < no_of_sites; site++) {
          (function(){
              var options = {
                  // ...
              };
      
              var req = http.request(options, function (res) {
                  // options available here
                  console.log(options);
              });
          }());
      }
      

      选项三

      似乎thisres.reqhttp.request() 回调中相同,但我不完全确定。

      【讨论】:

      • 感谢您的回答,虽然您的回答没有奏效,但经过一些实验,它引导我回答。
      • @sushant 真的吗?那对你有用吗?如果不正确,我想改进我的答案
      【解决方案3】:

      答案是 console.log(res.socket._httpMessage._headers.host);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-06-08
        • 2021-10-17
        • 2013-07-02
        • 1970-01-01
        • 1970-01-01
        • 2011-11-22
        • 2017-09-01
        • 1970-01-01
        相关资源
        最近更新 更多