搜尋

首頁  >  問答  >  主體

node.js - nodejs http请求,req.abort()和re.destory()的区别是什么?

在nodejs中进行http请求,设置超时,如果是req.abort() 那么http 请求还会是继续的,但是re.destory()就会彻底中止,他们详细区别是什么?

还有个超时问题,分为请求超时和响应超时,以前没这个概念,最近才认识到这个细节,我想问问这两个分别意味着什么?测试一个资源快慢,应该以哪个为标准?


var http = require('http');

var request_timer = null, req = null;
request_timer = setTimeout(function() {
    req.destroy();
    console.log('Request Timeout.');
    console.log('1');
}, 1000);
// 请求5秒超时

var options = {
    host: 'www.baidu.com',
    port: 80,
    path: '/'
}

req = http.get(options, function(e) {
    clearTimeout(request_timer);
}).on('error', function(err) {
    if(request_timer) {
        clearTimeout(request_timer);
        console.log('2');
    }
    console.log('3');
});

假设 timeout设置为 1ms(测试强制超时),req.destroy()的话 超时输出到3,直接退出,但是如果是req.abort()的话,等到输出3会过一会才会退出,按照nightire的说法,可能是请求已经发出,等待响应,所以req.abort()是没有影响的。

迷茫迷茫2866 天前611

全部回覆(2)我來回復

  • PHP中文网

    PHP中文网2017-04-17 11:10:57

    謝邀,在回家路上,所以長話短說:

    1. request.abort() 會中止一個已經發出的請求,但是你說請求還會繼續是什麼意思我看不懂,你是說執行它沒有效果嗎?

    2. re.destroy()?我隻知道 socket.destroy(),不知道你這個指的是什麼?socket.destroy() 會阻斷當前 socket 上的一切 I/O 活動,不僅僅是 HTTP 請求。這個通常是用來應對錯誤,而不是取消請求。但是我不知道你問題中的 re 指的是什麼,response 對象?好像沒有 destroy 方法吧。

    3. 請求是出去,響應是回來,這倆超時肯定是在不同的階段發生的。你問意味著什麼……我覺得已經很明顯了,一個出去一個回來,還能意味什麼呀?

    4. 至於測試一個資源的快慢,應該是綜合請求與響應的消耗來評定。如果你請求該資源遲遲得不到響應,你會感覺到慢;如果你請求很快得到響應,但是傳輸速度讓人崩潰,你還是會覺得慢。反之亦然。

    回覆
    0
  • 迷茫

    迷茫2017-04-17 11:10:57

    re.destroy()
    這個是繼承socket上的方法,調用後實際是調用socket.destory() .

    abort() 方法也會調用socket的destory

    ///這是node官方源碼 http.js的包

    ClientRequest.prototype.abort = function() {
    

    // If we're aborting, we don't care about any more response data.
    if (this.res)
    this.res._dump();
    else
    this.once('response', function(res) {
    res._dump();
    });

    if (this.socket) {
    // in-progress
    this.socket.destroy();////留意這裏
    } else {
    // haven't been assigned a socket yet.
    // this could be more efficient, it could
    // remove itself from the pending requests
    this._deferToConnect('destroy', []);
    }
    };

    //可以看出它的關係 about() 會更幹淨點

    回覆
    0
  • 取消回覆