Express JS Defining Routes


Defining routes in Express.js involves specifying how an application should respond to different HTTP requests based on the URL and HTTP method. Routes are fundamental to setting up the structure and behavior of a web application. Here's how you can define and manage routes in Express.js:

Basic Route Definition

A route in Express.js is defined using methods on the app object (e.g., app.get(), app.post(), app.put(), app.delete()). Each method specifies an HTTP method and a path, along with a callback function (the route handler) that is executed when a request matches the specified path and method.

Example:

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

Route parameters allow you to capture values from the URL and use them in your route handlers. Parameters are defined in the route path using a colon (:).

Example:

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 ? symbol. They are accessible via req.query.

Example:

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.

Route Methods

Express provides methods for different HTTP methods. Here’s how you can define routes for various methods:

  • GET: Retrieve data

    app.get('/path', (req, res) => { res.send('GET request'); });
  • POST: Create or submit data

    app.post('/path', (req, res) => { res.send('POST request'); });
  • PUT: Update data

    app.put('/path/:id', (req, res) => { res.send(`PUT request for ID ${req.params.id}`); });
  • DELETE: Delete data

    app.delete('/path/:id', (req, res) => { res.send(`DELETE request for ID ${req.params.id}`); });

Route Handling with Multiple Callbacks

You can define routes with multiple middleware functions or route handlers. Each function will execute in the order they are defined.

Example:

app.get('/path', [middleware1, middleware2], (req, res) => { res.send('Response from the final handler'); });

In this example, middleware1 and middleware2 will run before the final route handler.

Route Handler Functions

Route handlers are functions that take req (request), res (response), and optionally next (next middleware) as parameters.

Example:

app.get('/example', (req, res) => { res.send('Hello from /example'); });

Modularizing Routes with Routers

For larger applications, you can use Router objects to modularize routes. This helps in organizing routes into separate files or sections.

Example:

  1. Define Routes in a Router File (routes/users.js):

    const express = require('express'); const router = express.Router(); router.get('/', (req, res) => { res.send('Users list'); }); router.get('/:id', (req, res) => { res.send(`User ID: ${req.params.id}`); }); module.exports = router;
  2. Use Router in Main Application File (app.js):

    const express = require('express'); const app = express(); const usersRouter = require('./routes/users'); app.use('/users', usersRouter); app.listen(3000, () => { console.log('Server running on port 3000'); });

In this example:

  • Routes defined in routes/users.js are mounted under the /users path in the main application.

Summary

  • Defining Routes: Use methods like app.get(), app.post(), etc., to define how your application responds to HTTP requests.
  • Route Parameters: Capture dynamic values from the URL using parameters (:param).
  • Query Parameters: Access URL query parameters with req.query.
  • Route Methods: Handle different HTTP methods (GET, POST, PUT, DELETE).
  • Multiple Callbacks: Use multiple middleware functions or handlers for a route.
  • Modular Routes: Organize routes using Router objects for better structure in larger applications.

Defining routes effectively allows you to build a clear and maintainable structure for handling different requests in your Express.js application.