Skip to main content

expressjs-routes

Routes

The arguments which are available to an Express JS route handler-function are-

Req – the request object Res – the response object Next (optional) – a function which is used to pass control to one of the subsequent route handlers. The third argument is optional and may be omitted, but in some cases, it is useful where there is a chain of handlers and control can be passed to one of the subsequent route handlers skipping the current one.

Route Methods

Express supports methods that correspond to HTTP verbs: GET, POST, PUT, DELETE, and PATCH, among others. Each method is used for different purposes, reflecting the nature of the request. - GET: Requests data from a specified resource. - POST: Submits data to be processed to a specified resource. - PUT: Updates a specified resource. - DELETE: Deletes a specified resource. - PATCH: Partially updates a specified resource.

PATCH Method

The PATCH method is particularly interesting because it's used for partial updates to a resource, whereas PUT is used for full updates. Here's what makes PATCH unique: - Partial Update: With PATCH, you only need to send the data that you want to update, rather than the entire new version of the resource. This can reduce the amount of data sent between the client and the server, improving efficiency for large resources. - Idempotence: Technically, PATCH requests are not idempotent, which means making multiple identical PATCH requests may have different effects. However, it's possible to design your API in a way that PATCH requests are practically idempotent. - Use Case: PATCH is ideal for scenarios where resources are large, and changes are typically small. For example, updating a single field in a document or a record.

Example

Here's a simple example of using the Express Router to handle a PATCH request:

const express = require('express');
const router = express.Router();

// PATCH request to update a user's email
router.patch('/users/:id', (req, res) \=> {
  const { id } = req.params;
  const { email } = req.body;
  // Logic to update the user's email
  res.send(\`User \\\${id} email updated to \\${email}\`);
});

module.exports = router;

In this example, the router handles PATCH requests to /users/:id, allowing the client to update a user's email. This showcases the use of the PATCH method for partial updates within the modular and mountable structure provided by the Express Router.