如何检测用户取消请求
我正在通过编写一个非常基本的 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
}
}
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.
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.
Here's what I mean:
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
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
事实证明,我应该绑定到请求的“关闭”事件而不是“结束”事件。
这确实有道理。
我在这里发布此信息是为了其他可能遇到同样问题的人:
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: