Defining Routes
A route pairs an HTTP method and a URL pattern with a handler function. Express provides a method for each HTTP verb — app.get(), app.post(), app.put(), app.delete(), and so on.
Basic Routes
Console Output
Click “Run” to see the console output here.
Route Parameters
Console Output
Click “Run” to see the console output here.
Route Pattern Examples
| Pattern | Matches |
|---|---|
| /api/users/:id | Any single segment, captured as req.params.id |
| /api/users/:id/posts/:postId | Two captured parameters |
| /files/* | A wildcard matching any remaining path |
Organizing Routes with express.Router()
As an app grows past a handful of routes, express.Router() lets you group related routes into their own module — like all /api/users routes — which is then "mounted" onto the main app at a specific path prefix.
Splitting Routes Into a Router
Console Output
Click “Run” to see the console output here.
Best Practice
Split routes into separate Router modules by resource (users, orders, products) once an app grows past a handful of routes — it keeps app.js focused on wiring things together rather than containing every route handler.