如何检测用户取消请求

发布于 2024-11-03 07:22:47 字数 873 浏览 1 评论 0原文

我正在通过编写一个非常基本的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

甜味拾荒者 2024-11-10 07:22:47

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

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

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  
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文