CPCODELAB
Node.js

Building an HTTP Server

12 min read

Building an HTTP Server

Node.js includes the http module for creating web servers without any external dependencies. Understanding it deeply makes frameworks like Express much easier to learn, because they are just wrappers around this same module.

js
const http = require("http");

const server = http.createServer(function(req, res) {
  const url = req.url;
  const method = req.method;

  console.log(`${method} ${url}`);

  // Routing
  if (url === "/" && method === "GET") {
    res.writeHead(200, { "Content-Type": "text/html" });
    res.end("<h1>Welcome to my Node.js server!</h1>");

  } else if (url === "/api/status" && method === "GET") {
    res.writeHead(200, { "Content-Type": "application/json" });
    res.end(JSON.stringify({ status: "ok", uptime: process.uptime() }));

  } else {
    res.writeHead(404, { "Content-Type": "text/plain" });
    res.end("404 Not Found");
  }
});

const PORT = process.env.PORT || 3000;
server.listen(PORT, function() {
  console.log(`Server listening on http://localhost:${PORT}`);
});

Reading a POST Request Body

js
const http = require("http");

const server = http.createServer(function(req, res) {
  if (req.method === "POST" && req.url === "/echo") {
    let body = "";

    req.on("data", function(chunk) {
      body += chunk.toString();
    });

    req.on("end", function() {
      try {
        const parsed = JSON.parse(body);
        res.writeHead(200, { "Content-Type": "application/json" });
        res.end(JSON.stringify({ received: parsed }));
      } catch (err) {
        res.writeHead(400, { "Content-Type": "application/json" });
        res.end(JSON.stringify({ error: "Invalid JSON" }));
      }
    });
  }
});

server.listen(3000);

In production you will always use a framework like Express, Fastify, or Hono instead of the raw http module. But understanding the raw module removes the mystery from how those frameworks work internally.

Ready to test yourself?
Practice Node.js— quiz & coding exercises