Introducing Express
Express is a small, flexible web framework for Node.js. It sits on top of Node's built-in http module and gives you a cleaner way to define routes, read request data, send responses and plug in reusable functions called middleware. It is a common choice for building REST APIs that a React frontend talks to, and it is the "E" in the MERN stack.
What Express adds on top of plain Node
With only the http module, you check req.url and req.method yourself, collect the request body in chunks, parse JSON by hand and set headers manually. Express handles those chores:
- Routing:
app.get('/products/:id', handler)matches methods and paths, including parameters. - Request helpers:
req.params,req.queryandreq.body(with a body parser). - Response helpers:
res.json(),res.status(),res.send(),res.redirect(). - Middleware: a pipeline of functions for logging, parsing, auth and errors.
- Static files:
express.static()serves a folder of HTML, CSS and images.
Plain Node next to Express
// Plain Node
const http = require('http');
http.createServer((req, res) => {
if (req.method === 'GET' && req.url === '/api/hello') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ message: 'Hello' }));
} else {
res.writeHead(404);
res.end();
}
}).listen(3000);
// Express
const express = require('express');
const app = express();
app.get('/api/hello', (req, res) => {
res.json({ message: 'Hello' });
});
app.listen(3000);
Express also sends a 404 for unmatched routes automatically and sets the JSON content type for you.
How Express fits the RESTful idea
REST, from the previous lesson, maps HTTP methods onto resources. Express mirrors that directly: app.get, app.post, app.put, app.patch and app.delete. As an app grows, express.Router() lets you group routes for one resource in their own file and mount them under a prefix such as /api/products.
Installing it
mkdir shop-api && cd shop-api
npm init -y
npm install express
node server.js
Express is unopinionated: it does not decide your folder structure, database or template engine. That freedom is useful but means you make those choices yourself. A common structure separates routes, controllers, models and middleware into folders.
Early mistakes with Express
A very common one is reading req.body and getting undefined. Express does not parse request bodies by default; you must add app.use(express.json()) before your routes for JSON, or express.urlencoded({ extended: true }) for HTML form posts.
Another is forgetting to send a response in some branch of a handler, so the request hangs until it times out. Every route must end with res.json, res.send, res.end or a similar call, exactly once.
Many people also mix up req.params and req.query. In /products/42?sort=price, the 42 matched by /products/:id is in req.params.id, while sort is in req.query.sort. Both are strings.
Lastly, Express checks routes in the order they are defined. A parameter route such as app.get('/products/:id') placed before app.get('/products/new') will catch /products/new and treat "new" as an id. Put specific paths before parameter routes, and restart the server, or use a watcher like nodemon, after every change so you are not testing old code.
Key ideas
Express is a thin layer over Node that turns routing, parsing and responses into short readable code. Install it with npm, add the JSON parser, define routes per HTTP method, and use routers and middleware to keep the app organised as it grows.
Ready to master real-world web development?
Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.