In web development, routing refers to the process of directing client requests to specific server-side logic or resources. In the context of Node.js and its popular framework Express.js, routing is a fundamental concept that allows developers to define how different URLs should be handled by the application.
Express.js provides a simple yet powerful way to handle HTTP requests through routes. Each route can have one or more handler functions, which are executed when the route is matched. These handlers can perform various tasks such as fetching data from a database, rendering views, or sending JSON responses.
In Express.js, routing is handled using the app.METHOD(path, handler) syntax, where METHOD corresponds to an HTTP method (e.g., GET, POST), path is the URL path, and handler is the function that will be executed when a request matches the specified method and path.
The basic structure of defining a route in Express.js looks like this:
app.get('/', (req, res) => {
res.send('Hello World!');
});
In this example:
app.get() specifies that we are handling GET requests.'/' is the URL path.(req, res) => { ... } is the handler function.Express.js allows you to define route parameters in your routes. These parameters can be used to capture dynamic segments of a URL. For example:
app.get('/user/:id', (req, res) => {
res.send(`User ID: \${req.params.id}`);
});
In this case:
:id is a route parameter that captures the value from the URL path.req.params.id can be used to access the captured value in the handler function.A single route can have multiple handler functions. These handlers are executed sequentially, and each one has the opportunity to call next() to pass control to the next handler. If a handler does not call next(), the request-response cycle ends there.
app.get('/example', (req, res, next) => {
console.log('First handler');
next(); // Pass control to the next handler
}, (req, res) => {
res.send('Second handler');
});
In this example:
next() to pass control to the second handler.Express.js supports all standard HTTP methods such as GET, POST, PUT, DELETE, etc. Each method has its own corresponding function in Express.js:
app.get('/get', (req, res) => {
res.send('GET request');
});
app.post('/post', (req, res) => {
res.send('POST request');
});
app.put('/put', (req, res) => {
res.send('PUT request');
});
app.delete('/delete', (req, res) => {
res.send('DELETE request');
});
Route paths can be defined using strings or regular expressions. String-based routes are the most common and straightforward:
app.get('/about', (req, res) => {
res.send('About page');
});
Regular expression routes provide more flexibility but can be more complex:
app.get(/user\/(\w+)/, (req, res) => {
res.send(`User: \${req.params[0]}`);
});
In this example:
/user\/(\w+) matches URLs that start with /user/ followed by one or more word characters.req.params[0] captures the matched segment of the URL.Let's look at some practical examples to solidify our understanding of routing in Express.js.
Create a simple Express.js application with a basic GET route:
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(port, () => {
console.log(`Server running at http://localhost:\${port}`);
});
To run this application:
In the terminal, you should also see the log message "First handler".
Now that you have a solid understanding of routing in Express.js, the next step is to explore middleware functions. Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. They can execute any code, make changes to the request and the response objects, end the request-response cycle, and call the next middleware function.
Middleware functions are a powerful feature of Express.js that allow you to modularize your application logic and handle tasks such as authentication, logging, error handling, and more. Stay tuned for our next tutorial on Middleware Functions in Express.js!