HTTP Module in Node.js Tutorial: Server, Routing and JSON Examples

Build a Node.js server with the core HTTP module, then add query routing, streamed JSON parsing, precise status codes, and a small client. Worked requests and exercises make every step testable.

KnowledgeGate Team

Exam prep & CS education

Updated 4 Dec 20265 min read
HTTP Module in Node.js Tutorial: Server, Routing and JSON Examples

Express can hide the request-response mechanics that every Node.js web application depends on. The built-in HTTP module exposes those mechanics clearly, which makes it worth learning before a framework. Start one local server on 127.0.0.1:3000, route GET /jobs?id=42 and POST /sum, call the server from a Node client, test errors, and finish three exercises. Node.js and a terminal are enough; the Node.js, Express.js and MongoDB course is an optional guided path, not a prerequisite.

What the Node.js HTTP module actually does

According to the official Node.js HTTP documentation, require('node:http') loads the built-in, low-level HTTP client and server API. It handles HTTP message parsing and represents messages as streams, but it does not parse an application body such as JSON for you.

Four objects matter here. http.Server listens for connections. On the server, the request is an http.IncomingMessage, while the response is an http.ServerResponse. A client call creates an http.ClientRequest. The path is simple: a request reaches your handler, your code chooses the status, headers, and body, then it finishes the response.

Request bodies arrive through data events followed by end. One JSON document can be split across several chunks, so a chunk boundary is not a record boundary. If the protocol layer feels unfamiliar, revise HTML and HTTP and explore the wider Coding & Skills track.

Start a server and return the first response

Create server.js:

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

const server = http.createServer((req, res) => {
  res.writeHead(200, {
    'Content-Type': 'text/plain; charset=utf-8'
  });
  res.end('Hello from Node HTTP\n');
});

server.listen(3000, '127.0.0.1', () => {
  console.log('Server: http://127.0.0.1:3000');
});

Run it, then check it from a second terminal:

bash
node server.js
curl -i http://127.0.0.1:3000/

The essential output is status HTTP/1.1 200 OK, header Content-Type: text/plain; charset=utf-8, and body Hello from Node HTTP. createServer registers the request listener, writeHead sets the status and headers, and end sends the final data and finishes the response. Stop the process with Ctrl+C before replacing the file below.

HTTP request to Node server showing Content-Type text/plain; charset=utf-8 and a 200 response.

Route with req.method, req.url and status codes

Replace server.js with this routing server:

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

const jobs = new Map([
  [42, { id: 42, state: 'queued' }]
]);

const server = http.createServer((req, res) => {
  const url = new URL(req.url, 'http://127.0.0.1:3000');

  const sendJson = (statusCode, payload) => {
    const body = JSON.stringify(payload);
    res.writeHead(statusCode, {
      'Content-Type': 'application/json; charset=utf-8',
      'Content-Length': Buffer.byteLength(body)
    });
    res.end(body);
  };

  if (req.method === 'GET' && url.pathname === '/jobs') {
    const id = Number(url.searchParams.get('id'));
    const job = jobs.get(id);
    return job
      ? sendJson(200, job)
      : sendJson(404, { error: 'Job not found' });
  }

  return sendJson(404, { error: 'Route not found' });
});

server.listen(3000, '127.0.0.1', () => {
  console.log('Server: http://127.0.0.1:3000');
});

Restart with node server.js, then run these checks:

bash
curl -i 'http://127.0.0.1:3000/jobs?id=42'
curl -i 'http://127.0.0.1:3000/jobs?id=7'
curl -i http://127.0.0.1:3000/health

The first returns 200 with {"id":42,"state":"queued"}. The second returns 404 with {"error":"Job not found"}. The unmatched /health route returns 404 with {"error":"Route not found"}. Separating url.pathname from url.searchParams keeps routing separate from query data.

Read a streamed JSON body with POST /sum

Insert this branch immediately before the final fallback:

js
if (req.method === 'POST' && url.pathname === '/sum') {
  let raw = '';
  req.setEncoding('utf8');

  req.on('data', chunk => {
    raw += chunk;
  });

  req.on('end', () => {
    try {
      const { a, b } = JSON.parse(raw);
      if (!Number.isFinite(a) || !Number.isFinite(b)) {
        return sendJson(422, { error: 'a and b must be numbers' });
      }
      return sendJson(200, { result: a + b });
    } catch {
      return sendJson(400, { error: 'Invalid JSON' });
    }
  });

  return;
}

Test the successful path:

bash
curl -i -X POST http://127.0.0.1:3000/sum \
  -H 'Content-Type: application/json' \
  --data '{"a":18,"b":24}'

The ASCII body {"a":18,"b":24} is 15 bytes. Parsing gives the numbers 18 and 24; 18 + 24 = 42, so the response is status 200 with exactly {"result":42}.

Malformed body {"a":18,} fails JSON.parse and returns 400 with {"error":"Invalid JSON"}. Body {"a":18,"b":"24"} parses, but the string fails Number.isFinite, so it returns 422 with {"error":"a and b must be numbers"}. Collecting every chunk before parsing prevents partial JSON from being parsed. A production server should also enforce a body-size limit.

Sequence diagram showing a POST /sum request returning 42, with branches for invalid JSON and non-numeric values.

Make an outgoing request with http.get

Keep the server running and create client.js:

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

http.get('http://127.0.0.1:3000/jobs?id=42', (res) => {
  let body = '';
  res.setEncoding('utf8');
  res.on('data', chunk => {
    body += chunk;
  });
  res.on('end', () => {
    console.log(res.statusCode);
    console.log(body);
  });
}).on('error', error => console.error(error.message));

Run node client.js. Its exact output is:

Code
200
{"id":42,"state":"queued"}

The server's req and the client's res are both IncomingMessage objects, but one carries an incoming request and the other carries an incoming response. The Node.js documentation states that http.get uses GET by default and calls req.end() automatically. With http.request, the caller must call req.end(), even when sending no request body.

Common errors and a fast debugging checklist

  • EADDRINUSE means another process already uses 127.0.0.1:3000. Stop the earlier server with Ctrl+C, or change the port in both files.

  • ECONNREFUSED means the client could not reach the server. Start node server.js and wait for its printed URL.

  • ERR_HTTP_HEADERS_SENT usually means one branch sent JSON and then fell through to another response. Use return sendJson(...) for synchronous branches, and return after registering the POST listeners.

  • A POST that never completes often parses or replies before end, or a client built with http.request forgot req.end().

  • The core module does not create req.body, route parameters, or middleware. Validate method, path, JSON syntax, and numeric values separately. Database validation comes later, as explained in Mongoose schemas and models.

Assessment angles and three exercises

Typical questions ask you to identify IncomingMessage versus ServerResponse, explain why data can fire more than once before end, or spot the req.end() difference between http.get and http.request. Use the official Node.js documentation above as the authority for API behaviour.

  1. Add GET /double?n=21. Return 200 with {"result":42}. For missing or non-numeric n, return 400 with {"error":"n must be a number"}.

  2. Send {"a":13,"b":29} to /sum and require {"result":42}. Then confirm {"a":13,"b":"29"} still returns 422.

  3. Change client.js to request /jobs?id=7. It should print 404, then {"error":"Job not found"}.

The short version and the next step

  • Import the API with require('node:http').

  • Create a server and register one request listener.

  • Branch on the request method and parsed path.

  • Collect a request body until end, then parse it.

  • Finish exactly one response on every path.

  • Consume client response data and handle connection errors.

Keep 18 + 24 = 42 as the memory anchor: chunks become one JSON string, validation produces two numbers, and the handler produces one response. V8, libuv, event-loop ordering and CPU blocking belong to the earlier Node.js architecture tutorial; the raw HTTP path here begins at IncomingMessage and ends at ServerResponse. The earlier Express basics tutorial owns framework routing, express.json(), middleware order, and route parameters. The MERN Stack course is the next structured path from this server towards full-stack projects.

Rerun the three successful commands and the three failure cases, then complete all three exercises before moving to Express.