Express Router is a core feature of Express.js that helps in structuring applications efficiently. It allows developers to manage routes in a modular way, enhancing scalability in web development. This article provides a detailed guide on using the Express Router function effectively.
The Express Router function is part of Express.js that helps in organizing routes in separate files instead of managing all routes in a single file. It makes applications more efficient and manageable.
npm install express --save
We can define routes in a separate file to keep our application structured.
// routes/users.js
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => {
res.send('User List');
});
router.post('/add', (req, res) => {
res.send('User Added');
});
module.exports = router;
Now, we need to use the defined router in our main application file.
// app.js
const express = require('express');
const app = express();
const userRoutes = require('./routes/users');
app.use('/users', userRoutes);
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Middleware functions can be applied to routes to handle authentication, logging, or request modifications.
router.use((req, res, next) => {
console.log('Middleware executed');
next();
});
Dynamic parameters can be used to handle specific user requests.
router.get('/profile/:id', (req, res) => {
res.send(`User Profile ID: ${req.params.id}`);
});
Multiple handlers can be applied to a single route.
router.route('/posts')
.get((req, res) => res.send('Get Posts'))
.post((req, res) => res.send('Create Post'))
.put((req, res) => res.send('Update Post'));
Middleware can be applied only to specific routes instead of the whole app.
router.use('/admin', (req, res, next) => {
console.log('Admin Middleware');
next();
});
Express Router is a fundamental tool in Express.js that enhances efficiency in web development. It simplifies route handling, improves code maintainability, and provides a clean structure for building scalable applications.
Express Router is used to modularize routing in Express.js applications, making them more maintainable and scalable.
You can create a router using express.Router() and define routes separately.
Yes, middleware can be applied to routes to handle authentication, logging, and error handling.
app.use applies middleware to the whole application, whereas router.use applies middleware to specific routes.
Using Express Router helps in structuring large applications, reducing code duplication, and improving maintainability.
Copyrights © 2024 letsupdateskills All rights reserved