Module 42: Web Servers with Express

Lesson 2 of 5 · 15–25 minutes

Express basics

🏠The everyday picture

A ready-built counter with labelled trays, a stamp and a cash box, instead of building the counter yourself from planks.

📘What it really is

// src/app.ts
import express from "express";

export const app = express();
app.use(express.json());

app.get("/health", (req, res) => {
  res.json({ status: "ok" });
});
// src/server.ts
import { app } from "./app.ts";
import { config } from "./config.ts";

app.listen(config.port, () => {
  console.log(`API listening on http://localhost:${config.port}`);
});

🖱️Try it

Set up app.ts and server.ts as above. Run npm run dev and visit /health. Add a GET / route that returns the API's name and version.

✅Quick check

What does app.use(express.json()) do?

Show the answer

It reads JSON request bodies so they're available as req.body.

Why separate app.ts from server.ts?

Show the answer

Tests can use the app's routes directly without starting a server on a port.

← PreviousHTTP from the server's side
ProLearners Assist