You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Routing determines how an Express application responds to client requests for specific URLs and HTTP methods. Well-organised routing makes APIs easy to understand and maintain.
A route definition has three parts: the HTTP method, the path, and the handler function:
app.get("/", function (req, res) { res.send("GET /"); });
app.post("/items", function (req, res) { res.send("POST /items"); });
app.put("/items/:id",function (req, res) { res.send("PUT /items/" + req.params.id); });
app.delete("/items/:id", function (req, res) { res.send("DELETE /items/" + req.params.id); });
Named segments prefixed with : capture values from the URL:
app.get("/products/:category/:id", function (req, res) {
const { category, id } = req.params;
res.json({ category, id });
// GET /products/electronics/99 → { category: 'electronics', id: '99' }
});
Query string parameters are accessed via req.query:
app.get("/search", function (req, res) {
const { q, page } = req.query;
// GET /search?q=node&page=2
res.json({ query: q, page: page || "1" });
});
For large applications, grouping related routes into a Router keeps code modular:
// routes/users.js
const express = require("express");
const router = express.Router();
router.get("/", function (req, res) { res.json({ users: [] }); });
router.get("/:id", function (req, res) { res.json({ id: req.params.id }); });
router.post("/", function (req, res) { res.status(201).json({ created: true }); });
router.delete("/:id", function (req, res) { res.json({ deleted: req.params.id }); });
module.exports = router;
// app.js
const express = require("express");
const usersRouter = require("./routes/users");
const app = express();
app.use(express.json());
app.use("/users", usersRouter); // all routes prefixed with /users
app.listen(3000);
When multiple methods share the same path, use app.route() to avoid repetition:
app.route("/articles")
.get(function (req, res) { res.json({ articles: [] }); })
.post(function (req, res) { res.status(201).json({ created: true }); });
Add a catch-all route at the very end of your route definitions:
app.use(function (req, res) {
res.status(404).json({ error: "Route not found" });
});
Express matches routes in the order they are defined, so placing the 404 handler last ensures it only fires when no other route matched.
Good routing structure is the backbone of a maintainable API. Using Express Router to split routes into separate files by resource type scales cleanly as the application grows.
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.