Express JS and Node JS Routing and route handlers


In Node.js with Express.js, routing and route handlers are crucial for defining how an application responds to various HTTP requests. Here’s an overview of routing and route handlers:

Routing in Express.js

Routing is the process of defining the endpoints (URLs) that an application responds to and the logic that should be executed when those endpoints are accessed. In Express.js, routing is achieved through the use of app methods and Router objects.

Basic Routing

In Express, you define routes using HTTP methods like GET, POST, PUT, DELETE, etc. Each route is associated with a path and a handler function.

const express = require('express'); const app = express(); // Define a route for GET requests to the root URL app.get('/', (req, res) => { res.send('Hello, world!'); }); // Define a route for POST requests to /submit app.post('/submit', (req, res) => { res.send('Data received'); }); // Start the server app.listen(3000, () => { console.log('Server running on port 3000'); });

In this example:

  • app.get('/') handles GET requests to the root URL (/).
  • app.post('/submit') handles POST requests to /submit.

Route Parameters

You can define dynamic routes using route parameters. These parameters are placeholders in the route path that can be accessed via req.params.

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

In this example, :id is a route parameter. If you navigate to /users/123, req.params.id will be 123.

Query Parameters

Query parameters are part of the URL that comes after the ? in a query string. You can access them via req.query.

app.get('/search', (req, res) => { const term = req.query.term; res.send(`Search term is ${term}`); });

For a URL like /search?term=express, req.query.term will be express.

Router-Level Middleware

You can use the Router object to create modular route handlers. This helps in organizing routes for different parts of the application.

const express = require('express'); const app = express(); const router = express.Router(); // Define routes on the router router.get('/users', (req, res) => { res.send('Users list'); }); router.post('/users', (req, res) => { res.send('Create user'); }); // Use the router in the app app.use('/api', router); app.listen(3000, () => { console.log('Server running on port 3000'); });

In this example:

  • The router handles routes under the /api path.
  • /api/users responds to both GET and POST requests.

Route Handlers

Route handlers are functions that are executed when a route is matched. They receive the Request (req), Response (res), and next function as parameters.

Basic Route Handler

A route handler function can handle requests and send responses.

app.get('/hello', (req, res) => { res.send('Hello, world!'); });

Middleware Functions as Route Handlers

Middleware functions can be used as route handlers. They have access to the req, res, and next parameters.

const logMiddleware = (req, res, next) => { console.log(`Request method: ${req.method}, URL: ${req.url}`); next(); // Pass control to the next middleware or route handler }; app.use(logMiddleware); // Apply middleware globally app.get('/example', (req, res) => { res.send('Example route'); });

Error-Handling Middleware

Error-handling middleware is defined with four parameters: err, req, res, and next. It is used to catch and handle errors that occur during request processing.

app.use((err, req, res, next) => { console.error(err.stack); res.status(500).send('Something broke!'); });

Summary

  • Routing: Defines how an application responds to different HTTP requests based on the URL and HTTP method.
  • Route Handlers: Functions that process incoming requests and send responses.
  • Route Parameters: Dynamic segments in route paths.
  • Query Parameters: Parameters included in the URL query string.
  • Router-Level Middleware: Organizes routes and middleware into modular units.
  • Error-Handling Middleware: Catches and manages errors during request processing.

Routing and route handlers in Express.js provide a flexible way to manage and respond to HTTP requests, enabling you to build scalable and maintainable web applications.