Handbooks / Node.js / Chapter 5
Express Routing and Middleware
7 pages · ~5 min✓ Reviewed
Builds on Streams and Buffers. Next up: Error Handling and Async Patterns.
Express Mental Model and App Setup
1. What Express Is
- Express = thin Node HTTP layer; the app is a function
(req, res) - Each request goes through an ordered stack of middleware and route handlers
- First matching layer runs: it ends the response or calls
next() - If nothing responds, Express returns 404
- Request in
- First match runs
- Responds or next()
- No reply: 404
2. Minimal App
Routes, Params and Query Strings
1. Route Shape
app.METHOD(path, ...handlers): one verb, one pathapp.all()matches every methodapp.use()matches by path prefixapp.route('/books').get(list).post(create)chains one path
2. Params and Query
Request and Response Objects
1. Reading the request
| Field | Holds |
|---|---|
req.params | path values, strings |
req.query | URL query: strings or arrays |
req.body | needs a parser |
req.headers |
Middleware Chain, next() and Error Handling
1. What Middleware Is
- Signature:
(req, res, next) - Can change req or res
- Can end the response
- Or call
next()to pass control on
2. Order = Execution Order
- json()parse body
- authnext() or 401
- routeres.json
- error handlerlast
Built-in, Third-Party Middleware and Routers
1. Built-in and Third-Party
| Middleware | Does |
|---|---|
express.json() | fills req.body (JSON) |
express.urlencoded({ extended: true }) | fills req.body (forms) |
express.static('public') | serves files |
Express Cheat Sheet
1. Setup Order
- express()
- json, cors, helmet
- routers
- 404 handler
- error handler
- listen
2. Handlers and Status Codes
req.params.idpath,req.query.qURL,req.body.xneeds a parser- Reply with
res.status(n).json(obj) - Every middleware calls next() or responds
Check yourself
You register app.get('/users/:id', a) and then app.get('/users/me', b). Which handler runs for GET /users/me?
- Handler
a, withreq.params.id === 'me' - First match wins, so put
/users/mefirst
app.post('/items', h) reads req.body.name, but app.use(express.json()) comes after it. What happens?
req.bodyis still undefined, so reading.namethrows a TypeError