How to detect user cancels request

2019-04-10 01:47发布

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

2条回答
小情绪 Triste *
2楼-- · 2019-04-10 02:19

Do you perhaps want a timeout as answered here?

查看更多
3楼-- · 2019-04-10 02:24

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  
}
查看更多
登录 后发表回答