Implementing Routing and Middleware in Express.js.
Course Title: Mastering Express.js: Building Scalable Web Applications and APIs Section Title: Routing and Middleware Topic: Implement routing and middleware in an Express.js application to handle different HTTP methods and error scenarios.(Lab topic)
Overview:
In this hands-on exercise, you will learn how to implement routing and middleware in an Express.js application to handle different HTTP methods and error scenarios. You will apply the concepts you have learned so far in this course to create a robust and scalable web application.
Objective:
By the end of this lab, you will be able to:
- Create routes to handle different HTTP methods (GET, POST, PUT, DELETE) in Express.js
- Implement error handling middleware to handle and log errors
- Use custom middleware functions to validate and authenticate requests
- Apply routing and middleware to handle error scenarios
Lab Setup:
Before you begin, ensure that you have:
- A code editor or IDE of your choice
- Node.js and Express.js installed on your machine
- A basic Express.js application setup (refer to Node.js Official Documentation)
Step 1: Create Routes for Different HTTP Methods
Create a new file routes.js
in your project directory. In this file, define routes for different HTTP methods using Express.js route handlers:
const express = require('express');
const router = express.Router();
// GET route to retrieve all users
router.get('/users', (req, res) => {
// Return a list of users
res.json([{ name: 'John Doe' }, { name: 'Jane Doe' }]);
});
// POST route to create a new user
router.post('/users', (req, res) => {
// Create a new user and return the user data
const newUser = { name: req.body.name };
res.json(newUser);
});
// PUT route to update an existing user
router.put('/users/:id', (req, res) => {
// Update an existing user and return the updated user data
const updatedUser = { name: req.body.name, id: req.params.id };
res.json(updatedUser);
});
// DELETE route to delete a user
router.delete('/users/:id', (req, res) => {
// Delete a user and return a success message
res.json({ message: 'User deleted successfully' });
});
module.exports = router;
Step 2: Implement Error Handling Middleware
Create a new file error-handling-middleware.js
in your project directory. In this file, define an error handling middleware function using Express.js error handling middleware:
const express = require('express');
const logger = require('morgan');
const errorHandler = (err, req, res, next) => {
// Log the error using Morgan
logger.error(err.message);
// Return a 500 Internal Server Error response
res.status(500).json({ message: 'Internal Server Error' });
};
module.exports = errorHandler;
Step 3: Implement Custom Middleware Functions
Create a new file custom-middleware.js
in your project directory. In this file, define custom middleware functions to validate and authenticate requests:
const validateRequest = (req, res, next) => {
// Validate the request data
if (!req.body.name) {
return res.status(400).json({ message: 'Invalid request data' });
}
// Call the next middleware function in the stack
next();
};
const authenticateRequest = (req, res, next) => {
// Authenticate the request using a token-based approach
if (!req.headers.authorization) {
return res.status(401).json({ message: 'Unauthorized' });
}
// Call the next middleware function in the stack
next();
};
module.exports = { validateRequest, authenticateRequest };
Step 4: Apply Routing and Middleware to Handle Error Scenarios
In your app.js
file, apply the routing and middleware functions you created in the previous steps:
const express = require('express');
const app = express();
const router = require('./routes');
const errorHandler = require('./error-handling-middleware');
const { validateRequest, authenticateRequest } = require('./custom-middleware');
// Apply the validateRequest middleware function to the /users route
router.use(validateRequest);
// Apply the authenticateRequest middleware function to the /users route
router.use(authenticateRequest);
// Use the router module to handle routes
app.use('/api', router);
// Use the error handling middleware function to handle errors
app.use(errorHandler);
// Start the server
const port = 3000;
app.listen(port, () => {
console.log(`Server started on port ${port}`);
});
Conclusion:
In this lab, you implemented routing and middleware in an Express.js application to handle different HTTP methods and error scenarios. You applied custom middleware functions to validate and authenticate requests, and error handling middleware to log and handle errors.
Additional Resources:
- Express.js Documentation: Learn more about Express.js and its features.
- Node.js Documentation: Learn more about Node.js and its features.
**Do you have any questions or need help with this topic? Leave a comment below!
Images

Comments