Express.js Routes: Navigate To Your Web Application.

Express.js routes play a crucial role in determining how your application responds to different URLs. In this post, we’ll explore the world of Express.js routes and learn how to navigate your web application with ease.

Table of Contents

What are Express.js Routes?

Express.js routes are path that defines how your application responds to a specific URL. It’s essentially a mapping between a URL and a handler function that determines what happens when that URL is accessed. Routes can be defined using various HTTP methods, such as GET, POST, PUT, and DELETE.

Basic Route Structure:

  • HTTP Method: Specifies the type of request (e.g., GET, POST, PUT, DELETE).
  • Path: Defines the URL pattern to match.
  • Callback Function: Executes the logic associated with the route.

Types of Routes

There are several types of routes in Express.js, including:

  • Static Routes: These routes map a specific URL to a specific handler function.
  • Dynamic Routes: These routes use parameters to map a range of URLs to a single handler function.
  • Nested Routes: These routes allow you to define routes within routes, creating a hierarchical structure.

Creating Routes

1. Import the express.js module:

const express = require('express');
const app = express();

2. Defining Express.js Routes

To define a route in Express.js, you use the app.METHOD() function, where METHOD is the HTTP method you want to use (e.g., app.get(), app.post(), etc.). For example:

app.get('/', (req, res) => {
  res.send('GET Request to / Route');
});

app.post('/', (req, res) => {
  res.send('POST Request to / Route');
});

This defines a static route that responds to GET requests to the root URL (/) with the message “Hello World!”.

Express Route Methods

Express.js provides various methods to handle different HTTP request methods. Here’s a breakdown of the most commonly used ones:

GET

  • Purpose: Retrieves data from the server.
  • Example:
app.get('/users', (req, res) => {
    // Retrieve users from a database
    res.json(users);
  });

POST

  • Purpose: Sends data to the server to create or update resources.
  • Example:
app.post('/users', (req, res) => {
    // Create a new user based on the request body
    const newUser = req.body;
    // Save the user to the database
    res.status(201).json(newUser);
  });

PUT

  • Purpose: Updates an existing resource.
  • Example:
app.put('/users/:id', (req, res) => {
    const userId = req.params.id;
    const updatedUser = req.body;
    // Update the user with the given ID
    res.json(updatedUser);
  });

PATCH

  • Purpose: Partially updates an existing resource.
  • Example:
app.patch('/users/:id', (req, res) => {
    const userId = req.params.id;
    const updatedFields = req.body;
    // Update only the specified fields of the user
    res.json(updatedUser);
  });

DELETE

  • Purpose: Deletes a resource from the server.
  • Example:
app.delete('/users/:id', (req, res) => {
    const userId = req.params.id;
    // Delete the user with the given ID
    res.sendStatus(204);
  });

HEAD

  • Purpose: Similar to GET, but without the response body.
  • Example:
app.head('/users', (req, res) => {
    // Send a HEAD response with appropriate headers
    res.sendStatus(200);
  });

OPTIONS

  • Purpose: Returns information about the allowed HTTP methods for a given URL.
  • Example:
app.options('/users', (req, res) => {
    res.header('Allow', 'GET, POST, PUT, PATCH, DELETE');
    res.sendStatus(200);
  });

Other Methods

While less commonly used, Express also supports other HTTP methods like:

  • TRACE
  • CONNECT
  • COPY
  • MOVE
  • PROPFIND
  • PROPPATCH
  • MKCOL
  • LOCK
  • UNLOCK

Route Parameters

Route parameters allow you to capture values from the URL and pass them to your handler function.

  • Dynamic segments: Use colons (:) to define dynamic parts of the path.
  • Accessing parameters: Access the parameter value using the req.params object.

Example

app.get('/users/:id', (req, res) => {
  const id = req.params.id;
  res.send(`User ${id} found!`);
});

This defines a dynamic route that allows to handle requests for user information when user visits a URL like `/users/124` where 124 is User Id that can be any value.

Route Middleware:

  • Functions executed before the route callback.
  • Used for common tasks like authentication, authorization, and logging.

Example

// Middleware for /users route.
app.use('/users', (req, res, next) => { 
    // Authentication logic 
    next(); 
}); 

// /users route.
app.get('/users/:id', (req, res) => { 
    // User data 
    res.send("User data");
});

Route Methods

  • GET
  • POST
  • PUT
  • DELETE
  • PATCH
  • HEAD
  • OPTIONS

Advanced Routing Concepts:

  • Nested routes: Define routes within other routes.
  • Route groups: Group routes with a common prefix using app.use().
  • Route-level middleware: Apply middleware to specific routes.
  • Error handling middleware: Handle errors gracefully using app.use() with four arguments.

Best Practices:

  • Clear and concise routes: Use descriptive paths and meaningful names.
  • Modularization: Organize routes into separate files for better maintainability.
  • Testing: Write unit tests to ensure routes function as expected.
  • Security: Implement appropriate security measures to protect your application.

Additional Insights:

  • Route-level middleware: Apply middleware specifically to individual routes using the app.METHOD(path, middleware, callback) syntax.
  • Error handling middleware: Use app.use() with four arguments (req, res, next, err) to catch and handle errors that occur within your routes.
  • Route groups: Combine routes with a common prefix into a group using app.use() with a path parameter. This can simplify route definitions and improve organization.
  • Nested routes: Define routes within other routes to create hierarchical structures. This can be useful for organizing complex applications.
  • Route-level middleware: Apply middleware specifically to individual routes using the app.METHOD(path, middleware, callback) syntax.
  • Error handling middleware: Use app.use() with four arguments (req, res, next, err) to catch and handle errors that occur within your routes.
  • Route groups: Combine routes with a common prefix into a group using app.use() with a path parameter. This can simplify route definitions and improve organization.
  • Nested routes: Define routes within other routes to create hierarchical structures. This can be useful for organizing complex applications.

Conclusion

By understanding how to define static and dynamic routes, use route parameters, and create nested routes, you’ll be well on your way to building robust and scalable web applications. In next post we will explore the express.js middlewares.

You can learn more on official site of Express.js.

Want to run node.js on Android? Read how to install node.js in Termux.

Discover more from Easymux

Subscribe now to keep reading and get access to the full archive.

Continue reading