如何检测用户取消请求 [英] How to detect user cancels request

查看:112
本文介绍了如何检测用户取消请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying out Node.js by writing a very basic http/web caching proxy, and have hit something I haven't managed to break through.

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

Assuming I have a very basic proxy functionality (listen to request, pipe it to external server, wait for response, pipe it back to client), how do I detect when the client (web browser) cancels the request? When the user clicks "Stop"/Esc on his browser, the browser doesn't send me any "request" or info and attaching a callback for when the "response" connection ends doesn't get called.

这就是我的意思:

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  
    }
}


推荐答案

原来我应该绑定到关闭事件而不是请求的结束事件。
这实际上是有意义的。

我在这里发布这个可能遇到同样问题的其他人:

Turns out I should be binding to the "close" event instead of the "end" event of the request. That does actually make sense.
I'm posting this here for anyone else who might encounter the same issue:

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

这篇关于如何检测用户取消请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆