OnlineCBT Logo OnlineCBT
Node Tutorial
NODE · LESSON 6

HTTP Server Module (http.createServer)

By Ratan Updated: 16 Oct 2026

Create low-level HTTP web servers, handle request streams, and send HTTP responses.

Level: Beginner to Advanced
Duration: ~60 Mins Deep-Dive

Handle a request with Node's built-in HTTP server

HTTP connects a client's request to a server's response. A request includes a method, URL and headers. A response includes a status, headers and an optional body. Node's http module exposes these pieces directly. Express adds convenient routing and middleware on top of this foundation.

Create a small JSON service

Save server.mjs and run node server.mjs. No third-party package is required. The loopback address keeps this practice server accessible from your own computer.

import { createServer } from 'node:http';

function json(res, status, value) {
  res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8' });
  res.end(JSON.stringify(value));
}

const server = createServer((req, res) => {
  const url = new URL(req.url ?? '/', 'http://localhost');
  if (url.pathname !== '/health') {
    return json(res, 404, { error: 'Route not found' });
  }
  if (req.method !== 'GET') {
    res.setHeader('Allow', 'GET');
    return json(res, 405, { error: 'Use GET for this resource' });
  }
  return json(res, 200, { status: 'ok' });
});

server.on('error', error => {
  console.error('Server failed:', error.code ?? error.message);
  process.exitCode = 1;
});
server.listen(3000, '127.0.0.1', () => {
  console.log('Open http://127.0.0.1:3000/health');
});

Open the printed URL: the expected body is {"status":"ok"}. /missing returns 404. A POST request to /health returns 405 with an Allow header. The URL object separates the path from query parameters, so /health?check=1 still matches /health. The fixed base is used only to parse a relative URL, not to trust an incoming Host header.

End each response once

res.writeHead sends response metadata, and res.end completes the message. Return after responding so another branch does not attempt to send a second response. “Headers already sent” often means the same request reached two response paths. Leaving a request without end() makes the client wait.

Request bodies are streams

A JSON body can arrive in multiple chunks. It is not automatically available as req.body in the built-in module. If you implement body parsing, enforce a byte limit, handle aborted/error events, check Content-Type and catch JSON parsing failures. Never collect an unlimited upload into memory. The Express chapter demonstrates bounded JSON parsing with middleware.

Troubleshooting and practice

EADDRINUSE means another process is using the address/port. Stop your previous practice server with Ctrl+C or choose an available local port; repeatedly starting the same file does not replace the old process. Add GET /api/exams returning two public exam summaries, while keeping unknown paths as 404. Test method and path separately, and inspect the actual response status in browser developer tools or an HTTP client.

Deployment note: public hosting needs HTTPS termination, request limits, monitoring and an intentional network configuration. Changing the listening address alone does not make a service ready for public use.

📝 Live Lesson Practice

HTML/CSS JavaScript Python C++ C PHP
⌨️ Practice Inputs (लाइव इनपुट भरें) (खाली होने पर RED, भरने पर GREEN underline)
💻 Code Editor (Monaco VS Code Engine)
👀 Live Preview
पता संपर्क करें

+91 7877547686

ई-मेल

onlinecbtportal@gmail.com

हेल्पलाइन नंबर

+91 7877547686


डाउनलोड करने के लिए क्लिक करें
Get it on Google Play

ऐप डाउनलोड करने
के लिए Google Play पर
उपलब्ध है

WhatsApp Chat