Node.js ยท Chapter 17 of 43

Introduction to Express

Express is the most popular Node.js web framework. It simplifies routing, middleware, and request/response handling compared to the raw http module.

Install it with `npm install express`, then use it to build servers with far less boilerplate code.

Why Express?

Express provides a clean API for defining routes, handling middleware, parsing bodies, and serving static files, saving huge amounts of manual work.

A minimal app

An Express app is created with `express()`, routes are defined with methods like `.get()`, and the app starts with `.listen()`.

Example 1 (javascript)
const express = require('express');
const app = express();
app.get('/', (req, res) => {
  res.send('Hello Express!');
});
app.listen(3000, () => console.log('Server running'));
Output
Server running
(GET / returns 'Hello Express!')

Express dramatically reduces the code needed compared to raw http.

Example 2 (javascript)
app.get('/json', (req, res) => {
  res.json({ ok: true });
});
Output
{"ok":true}

res.json() automatically sets headers and stringifies the object.

Key points

  • Express is the most popular Node.js web framework.
  • It simplifies routing and middleware handling.
  • app.get(), app.post() etc. define routes for specific methods.
  • res.json() sends a JSON response automatically.
๐Ÿ’ก Note: Express doesn't replace Node.js โ€” it's built on top of the http module.

๐Ÿ“ Quick Quiz

1. How do you install Express?

2. What method sends a JSON response in Express?

3. What is Express built on top of?