Express 5 cheatsheet
Express 5: Routing
6 common Express 5 tasks.
Read a route parameter
Capture part of the URL as a parameter.
app.get("/users/:id", (req, res) => {
res.json({ id: req.params.id });
});
Read the query string
Read values such as ?page=2.
app.get("/search", (req, res) => {
res.json({ q: req.query.q });
});
Handle a JSON body
Parse JSON request bodies, then read req.body.
app.use(express.json());
app.post("/users", (req, res) => {
res.status(201).json(req.body);
});
Group routes in a router
Put related routes in a router and mount it under a prefix.
const router = express.Router();
router.get("/", (req, res) => res.json([]));
app.use("/users", router);
Send a status and JSON
Set the status code and send a JSON response.
res.status(404).json({ error: "Not found" });