Node.js ยท Chapter 18 of 43
Express Routing
Express routing maps HTTP methods and URL patterns to handler functions using methods like `app.get()`, `app.post()`, `app.put()`, and `app.delete()`.
Express also supports route parameters (like `/users/:id`) to capture dynamic parts of a URL.
Route methods
Each HTTP verb has a corresponding Express method, letting you define exactly how each endpoint should respond.
Route parameters
Segments prefixed with `:` in a route path become available on `req.params`, letting you build dynamic routes.
Example 1 (javascript)
app.get('/users/:id', (req, res) => {
res.send('User ID: ' + req.params.id);
});Output
User ID: 42Visiting /users/42 captures '42' as req.params.id.
Example 2 (javascript)
app.route('/books')
.get((req, res) => res.send('List books'))
.post((req, res) => res.send('Create book'));Output
List books / Create bookapp.route() chains multiple HTTP methods for the same path.
Key points
- app.get/post/put/delete map HTTP verbs to routes.
- Route params like :id are captured in req.params.
- app.route() chains methods for a single path.
- Routing is central to building REST APIs in Express.
๐ก Note: You can also use `express.Router()` to organize routes into separate files.
