Routing in Express.js
Routing in Express.js is the process of mapping incoming HTTP requests to specific functions that handle those requests. This allows you to create a structured and organized way to handle different requests to your web application.
Why is Routing Important?
Routing is essential for creating dynamic and interactive web applications. It allows you to:
- Handle different requests: You can define different routes for different actions, like displaying a homepage, creating a user account, or retrieving data from a database.
- Organize your code: Routing helps keep your code organized by separating different functionalities into dedicated routes and handlers.
- Improve maintainability: With well-defined routes, you can easily update or modify specific parts of your application without affecting other parts.
Defining Routes
In Express.js, you can define routes using the app.METHOD(path, handler)
syntax, where:
METHOD
: Represents the HTTP method (e.g.,GET
,POST
,PUT
,DELETE
).path
: Represents the URL path that the route will match.handler
: A function that will be executed when a request matching the specified path and method is received.
Example: Basic Routes
Here is an example of defining a few basic routes in Express.js:
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Welcome to the homepage!');
});
app.post('/users', (req, res) => {
// Handle user creation logic
res.send('User created successfully!');
});
app.get('/users/:id', (req, res) => {
// Handle user retrieval logic
const userId = req.params.id;
res.send(`User with ID: ${userId}`);
});
app.listen(3000, () => {
console.log('Server listening on port 3000');
});
In this example:
- The first route (
app.get('/', ...)
handles GET requests to the root path (/
) and sends a welcome message. - The second route (
app.post('/users', ...)
handles POST requests to the/users
path and handles user creation logic. - The third route (
app.get('/users/:id', ...)
handles GET requests to/users/:id
with a dynamic:id
parameter. It retrieves and displays information about the user with the specified ID.
Using Route Parameters
You can define dynamic routes using path parameters, which are denoted by colons (:
). These parameters allow you to extract information from the URL and use it in your route handlers.
app.get('/users/:id', (req, res) => {
const userId = req.params.id;
// Use userId to fetch user data from a database or other source
res.send(`User with ID: ${userId}`);
});
In this example, the :id
parameter captures the value from the URL. For example, if the URL is /users/123
, the userId
variable will be assigned the value 123
.
Routing Middleware
You can use middleware functions to perform actions before or after a request is handled by a route. Middleware functions are called in the order they are defined in your routes.
app.use((req, res, next) => {
console.log('Time:', Date.now());
next();
});
app.get('/', (req, res) => {
res.send('Hello world!');
});
In this example, the middleware function logs the current timestamp before proceeding to the next handler.
Nested Routes
You can define nested routes within a specific route path. This allows you to group related routes together.
const express = require('express');
const app = express();
const usersRouter = express.Router();
usersRouter.get('/', (req, res) => {
res.send('List of users');
});
usersRouter.get('/:id', (req, res) => {
const userId = req.params.id;
res.send(`User with ID: ${userId}`);
});
app.use('/users', usersRouter);
app.listen(3000, () => {
console.log('Server listening on port 3000');
});
In this example, we create a separate router (usersRouter
) to handle routes related to users. We then mount this router onto the /users
path using app.use('/users', usersRouter)
. This allows us to define all user-related routes within the usersRouter
object.
Resources
- Express.js Routing Documentation: https://expressjs.com/en/guide/routing.html
- Express.js Middleware Documentation: https://expressjs.com/en/guide/using-middleware.html
Top-Level Directory Explanations
routes/ - Subdirectory for defining the application’s routes, which map URLs to specific handlers.