Loading lessons...
Express Routing (GET, POST, PUT, DELETE)
Defining HTTP Route Handlers
Routing determines how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method.
const express = require("express");
const app = express();
app.use(express.json()); // Middleware to parse incoming JSON bodies
// GET: Retrieve resource list
app.get("/api/products", (req, res) => {
res.json([{ id: 1, name: "Laptop", price: 999 }]);
});
// POST: Create a new resource
app.post("/api/products", (req, res) => {
const newProduct = req.body;
res.status(201).json({ message: "Product created", product: newProduct });
});
// PUT: Update resource completely
app.put("/api/products/:id", (req, res) => {
const { id } = req.params;
res.json({ message: `Product ${id} updated`, data: req.body });
});
// DELETE: Remove resource
app.delete("/api/products/:id", (req, res) => {
const { id } = req.params;
res.status(200).json({ message: `Product ${id} deleted` });
});
Route Matching Rules
- Paths match string literals (
'/api/users'). - Paths match string patterns (
'/ab?cd','/users/:id'). - Methods match specific HTTP verbs (
app.get,app.post,app.put,app.delete,app.patch,app.all).
TL;DR
- Map HTTP CRUD verbs to Express routing methods: GET (Read), POST (Create), PUT/PATCH (Update), DELETE (Delete).