Search code examples
node.jshttpassert

Socket hangup error while using assert and http in node


I am trying to create a small http server using node (without using express). Here's the code for the HTTP server

const assert = require('node:assert');
const http = require('node:http');

const server = http.createServer((req, res) => {
  res.setHeader('content-length', 100);
  try {
    res.write('hello world');
  } catch (err) {
    assert(err instanceof Error);
  }
  res.end();
});

server.listen(0, () => {
  http.get({
    port: server.address().port
  });
});

When I add a try...catch statement before res.end(), I am getting this error

Error: socket hang up
    at connResetException (node:internal/errors:693:14)
    at Socket.socketOnEnd (node:_http_client:478:23)
    at Socket.emit (node:events:539:35)
    at endReadableNT (node:internal/streams/readable:1344:12)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21)
Emitted 'error' event on ClientRequest instance at:
    at Socket.socketOnEnd (node:_http_client:478:9)
    at Socket.emit (node:events:539:35)
    at endReadableNT (node:internal/streams/readable:1344:12)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
  code: 'ECONNRESET'
}

The assertion, setHeader and write are key components and cannot be removed.
How do I solve this error without removing them and still be able to assert on any errors on modifying the response?


Solution

  • try assigning a specific port to the server and then make requests on that port:

    server.listen(4004, () => {
      http.get({
        port: server.address().port
      });
    });