Skip to main content
Albero Academy

HTTP Servers & Express

Serve HTTP with the core module, then use Express for routing, middleware and clean request handling.

Chapter 3Node.js16 min readBeginner friendly
  • #Node.js
  • #Express
  • #HTTP

Node's original purpose was web servers. You can build one with the core http module, but almost everyone uses Express — a tiny framework that makes routing and middleware clean. This chapter builds up from raw HTTP to Express.

The http module

a raw server
import http from "http";
const server = http.createServer((req, res) => {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("Hello Albero");
});
server.listen(3000, () => console.log("http://localhost:3000"));

It works, but handling different URLs and methods by hand gets messy fast. That's what Express solves.

Express

terminal
npm install express
the same server, in Express
import express from "express";
const app = express();
app.get("/", (req, res) => {
res.send("Hello Albero");
});
app.listen(3000, () => console.log("http://localhost:3000"));

Routing

A route maps an HTTP method + path to a handler. Handlers get req (the request) and res (the response). Read params, query strings and the JSON body:

routes
app.get("/students/:id", (req, res) => {
res.json({ id: req.params.id }); // /students/42 → { id: "42" }
});
app.get("/search", (req, res) => {
res.json({ q: req.query.q }); // /search?q=data → { q: "data" }
});
app.post("/students", (req, res) => {
res.status(201).json(req.body); // needs express.json() (below)
});

Middleware

Middleware is a function that runs on the way in to your handlers — parsing bodies, logging, checking auth. Register it with app.use; call next() to continue:

middleware
app.use(express.json()); // parse JSON bodies into req.body
// A custom logger
app.use((req, res, next) => {
console.log(req.method, req.url);
next(); // pass control to the next middleware/route
});

Practice

Build an Express app with a logger middleware, a GET / that returns a welcome message, and a GET /programmes/:id that echoes the id as JSON. Test it in the browser and with a tool like curl.

Key takeaways

  1. 01The http core module can serve requests, but routing by hand gets messy.
  2. 02Express maps method + path to handlers with req/res — install with npm install express.
  3. 03Read input from req.params (URL), req.query (query string) and req.body (JSON).
  4. 04Middleware runs before handlers (parsing, logging, auth); call next() to continue.
  5. 05Register express.json() before routes that read the body — order matters.