如何检测用户取消请求

Cyc*_*nus 5 proxy http node.js

我正在通过编写一个非常基本的 http/web 缓存代理来尝试 Node.js,并且遇到了一些我无法突破的问题。

假设我有一个非常基本的代理功能(侦听请求,将其传送到外部服务器,等待响应,将其传送回客户端),我如何检测客户端(Web 浏览器)何时取消请求?当用户在浏览器上单击“停止”/Esc 时,浏览器不会向我发送任何“请求”或信息,并且不会调用“响应”连接结束时的回调。

这就是我的意思:

http.createServer (clientRequest, clientResponse) {  
    var client = http.createClient (port, hostname);
    var request = client.request (method, url, headers);  

    request.addListener ('response', function(response){  
        response.addListener ('data', function(chunk){  
           // forward data to clientResponse..
        }  
        response.addListener ('end', function(){   
           // end clientResponse..  
        }  
    });  
    clientResponse.addListener('end', function(){  
        // this never gets called :(
        // I want it to terminate the request/response created just above  
    }
}
Run Code Online (Sandbox Code Playgroud)

Cyc*_*nus 5

事实证明,我应该绑定到请求的“关闭”事件而不是“结束”事件。这确实有道理。
我在这里发布此信息是为了其他可能遇到同样问题的人:

clientResponse.addListener('close', function(){  
    // this gets called when the user terminates his request  
}
Run Code Online (Sandbox Code Playgroud)