Skip to Content
πŸŽ‰ Welcome to my notes πŸŽ‰
Express.jsBasic Routing & HTTP Methods πŸ›£οΈ

Basic Routing & HTTP Methods πŸ›£οΈ

Routing is the core of any web application. It’s the mechanism that determines how your application responds to a client’s request for a specific URL path and HTTP method. In Express, you define routes to map these incoming requests to specific handler functions.

Anatomy of a Route

The basic structure of a route definition in Express is simple and descriptive:

app.METHOD(PATH, HANDLER)

  1. app: The instance of your Express application.
  2. METHOD: A lowercase HTTP method (like get, post, put, or delete) that the route will respond to.
  3. PATH: The URL path on the server that will trigger this route.
  4. HANDLER: The function to be executed when the route is matched. This function receives the req and res objects.

Handling Common HTTP Methods

Express provides a distinct method for each of the primary HTTP verbs. These methods are often used to correspond with CRUD (Create, Read, Update, Delete) operations in a REST API.

  • app.get() (Read): Used to retrieve data. This is the most common method, used for fetching pages or API data.
  • app.post() (Create): Used to submit new data to the server, like creating a new user or posting a new blog entry.
  • app.put() (Update/Replace): Used to update an existing resource completely.
  • app.delete() (Delete): Used to delete a specified resource.

πŸ’» Code Example: A Simple CRUD API

index.js
const express = require("express"); const app = express(); app.use(express.json()); // Middleware to parse JSON bodies let items = [ { id: 1, name: "Laptop" }, { id: 2, name: "Keyboard" }, ]; // READ: Get all items app.get("/items", (req, res) => { res.json(items); }); // CREATE: Add a new item app.post("/items", (req, res) => { const newItem = { id: items.length + 1, name: req.body.name }; items.push(newItem); res.status(201).json(newItem); // 201 Created }); // UPDATE: Update an existing item app.put("/items/:id", (req, res) => { const itemId = parseInt(req.params.id); const item = items.find((i) => i.id === itemId); if (item) { item.name = req.body.name; res.json(item); } else { res.status(404).send("Item not found"); } }); // DELETE: Delete an item app.delete("/items/:id", (req, res) => { const itemId = parseInt(req.params.id); items = items.filter((i) => i.id !== itemId); res.status(204).send(); // 204 No Content }); app.listen(3000, () => console.log("Server running on port 3000"));

🚦 The Importance of Route Order

Express matches routes in the order they are defined in your code. When a request comes in, Express checks each route from top to bottom and executes the handler for the first one that matches.

This is especially important when dealing with dynamic routes (routes with parameters).

❌ Incorrect Order: If a generic, dynamic route like /users/:id is defined before a specific, static route like /users/new, the dynamic route will incorrectly catch the request, treating "new" as the :id.

index.js
// This route will incorrectly match a request for '/users/new' app.get("/users/:id", (req, res) => { res.send(`User profile for ID: ${req.params.id}`); }); // This route will NEVER be reached app.get("/users/new", (req, res) => { res.send("Form to create a new user"); });

βœ… Correct Order: Always place more specific, static routes before more generic, dynamic routes.

index.js
// This route is checked first app.get("/users/new", (req, res) => { res.send("Form to create a new user"); }); // This route is checked second app.get("/users/:id", (req, res) => { res.send(`User profile for ID: ${req.params.id}`); });

✨ Summary

  • Routing is how Express maps a request’s HTTP method and URL path to a specific handler function.
  • Express provides methods like app.get(), app.post(), app.put(), and app.delete() that directly correspond to the HTTP verbs and CRUD operations.
  • The order of your route definitions is crucial. Express uses the first matching route it finds, so specific routes should always be defined before dynamic ones.
Last updated on