Express.js is one of the most popular web application frameworks for Node.js. It provides a robust set of features for building web applications, including middleware support, routing, template engines, and more. In this module, we will focus on creating routes with Express and explore the fundamental aspects of routing in a Node.js application.
Table of Contents
- Introduction to Routing in Express
- Setting Up Express
- Defining Routes
- Route Parameters
- Query Parameters and URL Encoding
- Handling Different HTTP Methods
- Middleware in Routes
- Router Modules for Modularizing Routes
- Conclusion
1. Introduction to Routing in Express
In web applications, routes are the foundation of handling client requests. A route defines a path or URL on the server and the corresponding logic that should be executed when that path is accessed.
In Express, routes are created by defining methods that handle HTTP requests to specific endpoints. These methods respond to different types of requests (GET, POST, PUT, DELETE) and are associated with callback functions that handle the request.
2. Setting Up Express
Before we dive into creating routes, let’s set up a basic Express application. First, you need to install Express:
bashCopyEditnpm install express --save
Once Express is installed, you can set up a basic server by creating an app.js
file:
const express = require('express');
const app = express();
// Define the port
const port = 3000;
// Set up a basic route
app.get('/', (req, res) => {
res.send('Hello, Express!');
});
// Start the server
app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`);
});
Now, when you run the application with node app.js
and visit http://localhost:3000
, you should see the message “Hello, Express!”
3. Defining Routes
In Express, routes are defined using HTTP methods such as get
, post
, put
, delete
, etc. These methods are attached to specific paths to respond to client requests.
Here’s an example of defining a route that responds to a GET
request:
app.get('/about', (req, res) => {
res.send('This is the About page');
});
In this case, when a client sends a GET
request to /about
, the server will respond with the message “This is the About page.”
You can define multiple routes for different paths:
app.get('/home', (req, res) => {
res.send('Welcome to the Home page!');
});
app.get('/contact', (req, res) => {
res.send('Contact us at [email protected]');
});
4. Route Parameters
Route parameters allow you to capture values from the URL and use them within your route handler. For example, you might want to create a route that dynamically responds based on a user’s ID or a product’s name.
You can define a route with parameters using a colon (:
) in the route path:
app.get('/user/:id', (req, res) => {
const userId = req.params.id;
res.send(`User ID: ${userId}`);
});
In this case, when you visit /user/123
, the response will be “User ID: 123”. You can also use multiple parameters in a route:
app.get('/product/:category/:id', (req, res) => {
const category = req.params.category;
const productId = req.params.id;
res.send(`Category: ${category}, Product ID: ${productId}`);
});
5. Query Parameters and URL Encoding
In addition to route parameters, Express also supports query parameters. Query parameters are typically used to pass additional data to the server via the URL, like search terms, page numbers, etc.
Here’s an example of handling query parameters:
app.get('/search', (req, res) => {
const query = req.query.q; // Get the 'q' query parameter
res.send(`Search results for: ${query}`);
});
For example, a URL like /search?q=nodejs
will respond with “Search results for: nodejs”.
Query parameters are key-value pairs appended to the URL. They are useful when you need to send additional data in a request, especially for searches, filters, and pagination.
6. Handling Different HTTP Methods
Express allows you to handle different types of HTTP requests, including GET
, POST
, PUT
, DELETE
, etc.
- GET: Retrieves data from the server
- POST: Sends data to the server (e.g., form submission)
- PUT: Updates data on the server
- DELETE: Deletes data from the server
Here’s an example for handling POST requests:
app.post('/submit', (req, res) => {
res.send('Data received via POST request');
});
For PUT and DELETE requests, you can define routes in a similar way:
app.put('/update/:id', (req, res) => {
res.send(`Updating resource with ID: ${req.params.id}`);
});
app.delete('/delete/:id', (req, res) => {
res.send(`Deleting resource with ID: ${req.params.id}`);
});
7. Middleware in Routes
Express provides a powerful middleware mechanism that allows you to intercept requests before they reach the route handler. You can use middleware for tasks like logging, authentication, validation, and more.
You can define middleware functions that run for all routes or specific routes:
Example: Logging Middleware
app.use((req, res, next) => {
console.log(`${req.method} request made to ${req.url}`);
next(); // Pass control to the next middleware or route handler
});
Example: Middleware for Specific Routes
app.get('/profile', (req, res, next) => {
console.log('Accessing the profile page');
next();
}, (req, res) => {
res.send('Welcome to the profile page');
});
You can also use middleware to handle route-specific tasks, such as validating request data or checking user authentication.
8. Router Modules for Modularizing Routes
For larger applications, it’s a good idea to organize your routes into separate files or modules. Express allows you to use the Router
object to modularize your routes and keep your code clean.
Step 1: Create a Router File
Create a file called routes.js
:
const express = require('express');
const router = express.Router();
router.get('/about', (req, res) => {
res.send('About Us');
});
router.get('/contact', (req, res) => {
res.send('Contact Us');
});
module.exports = router;
Step 2: Use the Router in Your Main Application
const express = require('express');
const app = express();
const routes = require('./routes');
app.use('/', routes);
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
Now, the routes are defined in a separate file and can be easily maintained and scaled.
9. Conclusion
In this module, we learned how to create routes in Express, handle different HTTP methods, use route parameters, work with query parameters, and apply middleware to routes. We also explored how to modularize routes for better organization using Express Router.
Routes are a fundamental part of building web applications, and mastering them is essential for creating functional APIs and dynamic websites. As you progress, you’ll be able to combine routes with other Node.js features to build powerful web applications.