簡體   English   中英

如何在node.js的http響應中獲取主機名?

[英]How to get host name in http response in node.js?

我正在使用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;
        }
    });
}

選項一 :使用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);
        });
    }());
}

選項三

看來this是一樣的res.reqhttp.request()回調,但我不能完全肯定。

我們可以在this對象中獲得宿主站點。

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM