Node.js
Method chaining
Learn method chaining with app.route.
Method chaining: app.route
app.route(path) is the way to chain multiple HTTP methods on the same path. Example: app.route("/items").get(getHandler).post(postHandler);. This defines both GET /items and POST /items in one place.
Method chaining lets you write the path once and add all methods in sequence. You call .get(), .post(), .put(), .delete() in turn. This gathers all operations of a resource in one place: read, create, update, delete. The code is more readable and path repetition is avoided. Instead of writing the same path separately with app.get and app.post, you write one chain with app.route.
The advantage of chaining
Without app.route, writing two routes on the same path looks like this: app.get("/items", h1); app.post("/items", h2);. The path "/items" is written twice. With app.route the path is written once: app.route("/items").get(h1).post(h2);.
This small difference matters in large projects. When the path changes (say from /items to /products), you update one place. Also, since all operations are together, you see the full API of a resource at a glance. This is a common pattern in REST API design. app.route also works on a router: router.route("/items").... This combines modular routers with method chaining.
Exercise Write chained routes with app.route
Define app.route("/items").get((req, res) => res.send("Items")).post((req, res) => res.send("Added")). The server makes a GET request to /items.
Show example solution
const express = require("express");
const app = express();
app.route("/items")
.get((req, res) => res.send("Items"))
.post((req, res) => res.send("Added"));
const server = app.listen(3000, () => {
const http = require("http");
http.get("http://localhost:3000/items", (res) => {
let body = "";
res.on("data", (c) => body += c);
res.on("end", () => { console.log("Reply: " + body); server.close(); });
});
});
Test yourself
-
Complete the app.route chain
app.route("/items")
.____((req, res) => res.send("Öğeler"))
.post((req, res) => res.send("Eklendi"));
Show answer
app.route("/items")
.get((req, res) => res.send("Öğeler"))
.post((req, res) => res.send("Eklendi"));
-
Match each piece to its role
- app.route('/items')
- Defines the path once
- .get(...)
- Adds the GET method
- .post(...)
- Adds the POST method
- .delete(...)
- Adds the DELETE method
-
What does app.route('/items').get(h1).post(h2) define?
app.route("/items").get(h1).post(h2)
- Only GET /items
- Only POST /items
- Two separate paths
- Hem GET hem POST /items
Show answer
Hem GET hem POST /items — The chain defines both GET and POST /items.
Next lesson: Summary - Routing