簡體   English   中英

終止Node.js服務器請求的正確方法是什么?

[英]What's the proper way of terminating a Node.js server request?

我正在玩一個基本的Node.js服務器(沒有框架)。 我希望服務器在某些條件下終止請求。 這樣做的正確方法是什么? 我嘗試了request.connection.destroy()req.removeListener('data')req.removeListener('end') ,但是服務器一直運行並返回結果。 這是我擁有的一部分:

http.createServer(function(req,res){
    req.on('data',function(data){
        content+=data;
        if(condition){
            req.connection.destroy();
            req.removeListener('data');
            req.removeListener('end');
        }
    });

    req.on('end',function(){=
        res.writeHead(200,{
            'Context-Type':'text/plain',
        });
        res.write(content);
        res.end();
    });
});

PS做req.once('end',...)而不是req.on('end',...)更好嗎? 其他人似乎都在使用on() ,這是否有原因?

編輯:我將if正文更改為:

                req.abort();
                req.connection.destroy();
                req.removeAllListeners('data');
                req.removeAllListeners('end');

但是, end事件仍在被調用(即仍在編寫content )。

您應該調用req.abort();

此處的文檔: https : //nodejs.org/api/http.html#http_request_abort

您必須返回任何結果。 這只是正確的方法。 您的客戶端向服務器發送請求,因此需要回答。 可以是狀態400,但必須是。 換句話說,您的客戶端將永遠不會意識到請求已被終止,從而降低了您的應用程序的速度。

暫無
暫無

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

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