π Handling Different HTTP Methods in Express
Express makes handling HTTP methods incredibly straightforward by providing a dedicated method for each one. This allows you to map specific actions to specific HTTP verbs for any given URL.
Think of your applicationβs endpoint (e.g., /users) as a multi-purpose service desk. The HTTP method is the instruction you give the clerk.
GET /users: βIβd like to get a list of all users.βPOST /users: βIβd like to submit this form for a new user.βPUT /users/123: βIβd like to replace the entire file for user 123 with this new one.βDELETE /users/123: βIβd like to delete the file for user 123.β
Express provides a direct and semantic way to set up these βservice windows.β
π οΈ The Core CRUD Methods
These four methods are the foundation of most web APIs, corresponding to Create, Read, Update, and Delete operations.
π₯ GET: Read Data
The GET method is used to retrieve data. It should be a safe operation, meaning it doesnβt change the state of the server. Itβs also idempotent, meaning making the same GET request multiple times will produce the same result.
// Get a list of all users
app.get("/users", (req, res) => {
// Logic to fetch users from a database
res.json(users);
});
// Get a single user by their ID
app.get("/users/:id", (req, res) => { // /:id - Dynamic Route Parameter
const userId = req.params.id;
// Logic to fetch a specific user
res.json(user);
});π€ POST: Create Data
The POST method is used to submit a new entity to the server, resulting in a new resource being created. POST is not idempotent; making the same POST request twice will create two separate resources.
// Create a new user
app.post("/users", (req, res) => {
const newUser = req.body;
// Logic to save the new user to a database
res.status(201).json(newUser);
});π PUT: Update/Replace Data
The PUT method is used to completely replace an existing resource. The client sends the full, updated representation of the resource. PUT is idempotent; updating a resource with the same data multiple times has the same effect as doing it once.
// Update an existing user
app.put("/users/:id", (req, res) => {
const userId = req.params.id;
const updatedUser = req.body;
// Logic to update the user in the database
res.json(updatedUser);
});ποΈ DELETE: Remove Data
The DELETE method does exactly what its name implies: it removes a specific resource. Itβs also considered idempotent, as deleting a resource multiple times has the same outcome as deleting it once (the resource is gone).
// Delete a user
app.delete("/users/:id", (req, res) => {
const userId = req.params.id;
// Logic to delete the user from the database
res.status(204).send(); // 204 No Content is a common success response
});β¨ Other Useful Methods
PATCH: Similar toPUT, but used for partial updates. Instead of replacing the entire resource, you only send the fields you want to change.app.all(): This is a special method that matches all HTTP verbs for a given route. Itβs great for applying specific middleware to a route, like an authentication check, regardless of whether itβs aGET,POST, orDELETErequest.
π Chaining with app.route() for Cleaner Code
For endpoints that support multiple HTTP methods, Express allows you to chain the handlers together for a cleaner, more organized structure. This avoids repeating the route path and is a hallmark of professional Express code.
app
.route("/users/:id")
.get((req, res) => {
// Handle GET: retrieve a user
res.send(`Get user with ID ${req.params.id}`);
})
.put((req, res) => {
// Handle PUT: update a user
res.send(`Update user with ID ${req.params.id}`);
})
.delete((req, res) => {
// Handle DELETE: remove a user
res.send(`Delete user with ID ${req.params.id}`);
});