In Express.js, route handlers are a core feature that allows developers to define the behavior for specific HTTP requests. When building web applications, it's crucial to handle requests efficiently. Route handlers provide a way to map different request URLs and methods (such as GET, POST, PUT, and DELETE) to specific functions.
What Are Route Handlers?
An Express.js route handler is a function that determines how the application responds to client requests at a particular endpoint. The endpoint is defined by a URL path and an HTTP method (GET, POST, PUT, DELETE, etc.).
Defining Routes for Different HTTP Methods
Express.js allows you to define route handlers for various HTTP methods. Below are examples of handling common HTTP requests like GET, POST, PUT, and DELETE.
Handling GET Requests
You use a GET request to retrieve data from the server. Here's an example of how to handle a GET request in Express.
Example:
// app.js
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Welcome to the homepage!');
});
app.get('/users', (req, res) => {
// Simulate fetching user data
const users = [{ id: 1, name: 'Alex' }, { id: 2, name: 'Jane' }];
res.json(users);
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
In this example, the root route (/
) responds with a welcome message, and /users
responds with a list of users in JSON format.
Handling POST Requests
The POST method sends data to the server, typically when creating a new record.
Example:
// app.js
app.use(express.json()); // To parse JSON bodies
app.post('/users', (req, res) => {
const newUser = req.body;
// Simulate adding a new user
res.status(201).send(`New user ${newUser.name} added successfully.`);
});
In the above code, the server accepts a new user record sent in the request body and responds with a confirmation message.
Handling PUT Requests
You use a PUT request to update existing data. The following example uses a route parameter (:id
) to identify the user's record that needs updating.
Example:
// app.js
app.put('/users/:id', (req, res) => {
const userId = req.params.id;
const updatedData = req.body;
// Simulate updating user data
res.send(`User record with ID: ${userId} updated successfully.`);
});
In the above example, the route /users/:id
allows the client to update a specific user's data based on the id
parameter.
Handling DELETE Requests
DELETE requests remove data from the server. Here's how you handle a DELETE request in Express.
Example:
// app.js
app.delete('/users/:id', (req, res) => {
const userId = req.params.id;
// Simulate deleting user data
res.send(`User record with ID: ${userId} deleted successfully.`);
});
In the above example, the server handles deleting a user's record identified by the id parameter.
Chaining Route Handlers
In Express.js, you can chain route handlers for the same path but with different HTTP methods. This method eliminates redundancy when defining routes for similar paths. Using app.route()
, you can group multiple methods (GET, POST, PUT) for a single endpoint, keeping the code clean and easy to manage.
Example:
// app.js
app.route('/user')
.get((req, res) => {
// Fetch user data
res.send('Fetching user data');
})
.post((req, res) => {
// Add a new user
res.send('New user created');
})
.put((req, res) => {
// Update user data
res.send('User data updated');
});
The above example /user
route responds to GET, POST, and PUT requests in a streamlined manner.
Conclusion
This tutorial taught you how to create and implement route handlers in Express.js for different HTTP methods. By understanding route handlers, you can efficiently manage HTTP requests in your Express applications and ensure your server responds correctly to various routes and methods.