How do you handle routing in Express.js?
Routing in Express.js refers to defining routes that map HTTP requests to specific handler functions. Express.js provides a straightforward and flexible routing mechanism that allows developers to define routes for various HTTP methods (GET, POST, PUT, DELETE, etc.) and URL patterns.
Here’s how you can handle routing in Express.js:
- Define an Express application: First, create an instance of the Express application using the express() function.
- Define route handlers: Define route handler functions to handle incoming requests. Route handlers are functions that take two arguments: req (the request object) and res (the response object).
- Define routes: Use the app.get(), app.post(), app.put(), app.delete(), etc., methods to define routes for handling specific HTTP methods and URL patterns. Pass the route path and the corresponding route handler function as arguments to these methods.
- Use middleware: Optionally, you can use middleware functions to preprocess requests before they reach the route handler functions. Middleware functions can perform tasks such as logging, authentication, request parsing, and error handling.
Here’s an example of handling routing in Express.js:
javascript Copy code const express = require('express'); const app = express(); // Define a route handler for the homepage app.get('/', (req, res) => { res.send('Welcome to the homepage!'); }); // Define a route handler for the /about page app.get('/about', (req, res) => { res.send('About Us'); }); // Start the Express.js server app.listen(3000, () => { console.log('Server is running on port 3000'); });
In this example, we define two routes: one for the homepage (/) and another for the about page (/about). Each route has a corresponding route handler function that sends a response to the client.
Express.js’s routing mechanism is flexible and supports various features such as route parameters, route middleware, route nesting, and route grouping, allowing developers to build complex and feature-rich web
applications.