Skip to Content
πŸŽ‰ Welcome to my notes πŸŽ‰
Express.jsπŸ”€ Handling Different HTTP Methods in Express

πŸ”€ 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.

httpMethods.js
// 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.

httpMethods.js
// 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.

httpMethods.js
// 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).

httpMethods.js
// 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 to PUT, 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 a GET, POST, or DELETE request.

πŸ”— 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.

httpMethods.js
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}`); });
Last updated on