I have a simple proxy server as below:
const http = require('http');
function onRequest(request, response) {
console.log('serve: ' + request.url);
const options = {
hostname: 'www.google.com',
port: 80,
path: request.url,
method: 'GET'
};
let proxy = http.request(options, function (res) {
res.pipe(response);
});
request.on('close', () => {
console.log('Request Closed');
proxy.destroy();
});
request.pipe(proxy);
}
http.createServer(onRequest).listen(8888);
I added a close listener on the request event, so I could destroy the proxy if the request connection is closed. The main problem is the close event fired earlier than expected and I got the following error:
Request Closed
node:events:368
throw er; // Unhandled 'error' event
^
Error: socket hang up
at connResetException (node:internal/errors:691:14)
at Socket.socketCloseListener (node:_http_client:420:25)
at Socket.emit (node:events:402:35)
at TCP.<anonymous> (node:net:687:12)
Emitted 'error' event on ClientRequest instance at:
at ClientRequest.onerror (node:internal/streams/readable:773:14)
at ClientRequest.emit (node:events:390:28)
at Socket.socketCloseListener (node:_http_client:420:11)
at Socket.emit (node:events:402:35)
at TCP.<anonymous> (node:net:687:12) {
code: 'ECONNRESET'
}
This becomes weird because everything works fine on node.js v14/v12.
P.S: I know there is a way in which I can solve the problem by changing request to response for the close listener, but I'm looking for the reason.