Labs ICT
โญ Pro Login

HTTP Module

Create a web server from scratch.

HTTP Module

The http module lets you create web servers without any framework. It is the foundation that Express.js is built on.

Creating a Basic Server

const http = require("http");

const server = http.createServer((req, res) => {
  res.writeHead(200, { "Content-Type": "text/plain" });
  res.end("Hello from Node.js!");
});

server.listen(3000, () => {
  console.log("Server running on http://localhost:3000");
});
Try it Yourself โ†’

Handling Different Routes

const http = require("http");

const server = http.createServer((req, res) => {
  if (req.url === "/" && req.method === "GET") {
    res.writeHead(200, { "Content-Type": "text/html" });
    res.end("<h1>Home Page</h1>");
  } else if (req.url === "/api/users" && req.method === "GET") {
    res.writeHead(200, { "Content-Type": "application/json" });
    res.end(JSON.stringify([{ name: "Alice" }]));
  } else {
    res.writeHead(404);
    res.end("Not Found");
  }
});

Reading Request Body

const server = http.createServer((req, res) => {
  let body = "";

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

  req.on("end", () => {
    const parsed = JSON.parse(body);
    console.log("Received:", parsed);
    res.writeHead(201);
    res.end("Created");
  });
});

Making HTTP Requests

const http = require("http");

// GET request
http.get("http://api.example.com/users", (res) => {
  let data = "";
  res.on("data", (chunk) => { data += chunk; });
  res.on("end", () => {
    console.log(JSON.parse(data));
  });
});

Pro Tip: For production servers, use Express.js instead. The raw HTTP module is great for learning, but Express handles routing, middleware, and error handling much better.

๐Ÿงช Quick Quiz

Which method is used to create an HTTP server?