Routing in Express.js refers to how an application's endpoints (URIs) respond to client requests. This tutorial will cover the basics of Express routing.
Understanding Routing
Routing in Express.js defines URL patterns (endpoints) and links them with specific actions or resources within your web application. It allows users to navigate your application based on URLs. Express uses the app object to define routes.
Syntax:
app.METHOD(PATH, HANDLER)
Each route consists of three parts:
- METHOD: Specifies the HTTP request method. Common methods include GET, POST, PUT, DELETE, etc.
- PATH: Defines the URL pattern for the route. (e.g., /about, /contact).
- HANDLER: The function that is executed when a route is matched. It typically sends a response back to the client.
Basic Routing with GET Requests
Here's an example showing basic routing with GET requests:
Example:
const express = require('express'); // Import express module
const app = express(); // Create express app
const port = 3000; // Define port
// Define a route for the root URL ('/') with a GET request method
app.get('/', (req, res) => {
// Send a response to the client
res.send('Welcome to the Home Page!');
});
// Define a route for the '/about' URL with a GET request method
app.get('/about', (req, res) => {
// Send a response to the client
res.send('About Us');
});
// Define a route for the '/contact' URL with a GET request method
app.get('/contact', (req, res) => {
// Send a response to the client
res.send('Contact Us');
});
// Start server
app.listen(port, () => console.log(`Server is running at http://localhost:${port}`));
Explanation:
- The root route (
/
) handles GET requests for the root URL. When a request is received at this URL, the handler function sends 'Welcome to the Home Page!' as a response. - The about route (
/about
) handles GET requests for the/about
URL. When a GET request is made to/about
, the handler function sends 'About Us' as a response. - The contact route (
/contact
) handles GET requests for the/contact
URL. When a request is received at this URL, the handler function sends 'Contact Us' as a response.
Conclusion
This tutorial has provided a foundation for understanding routing in Express.js. Mastering routing allows you to build dynamic and user-friendly web applications. As you progress, explore advanced topics on routing, such as route parameters, middleware, and nested routes.