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)
app: The instance of your Express application.METHOD: A lowercase HTTP method (likeget,post,put, ordelete) that the route will respond to.PATH: The URL path on the server that will trigger this route.HANDLER: The function to be executed when the route is matched. This function receives thereqandresobjects.
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
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.
// 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.
// 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(), andapp.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.