Routes
Routes map a method and a URL path to the function that handles it.
In this page:
Syntax
app.get('/path', (req, res) => {
res.send('response');
});
app.post('/path', handler);
app.put('/path/:id', handler);
app.delete('/path/:id', handler);
Routes
Define routes with app.get, app.post, app.put and app.delete. Paths can contain parameters such as /users/:id available in req.params. Routes are checked in the order defined and the first that responds wins.
Note:
Use express.Router to group related routes in separate files.
Example: Routes
const express = require("express");
const app = express();
app.get("/", (req, res) => res.send("home"));
app.get("/users/:id", (req, res) => res.json({ id: req.params.id }));
app.post("/users", express.json(), (req, res) => res.status(201).json(req.body));
app.listen(3000, () => console.log("listening on 3000"));
// GET /users/42 -> {"id":"42"}
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Defining a catch-all before specific routes
- Forgetting to respond
- Using the wrong HTTP method
Chapter Summary
- app.METHOD(path, handler)
- :id creates params
- Order matters
- Router groups routes
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: