Phone: +91 - 7503630654 Email: warriorsitech@gmail.com
Express Router, a part of the Express.js framework, provides a modular way to organize routes in Node.js applications. This guide explores how to leverage Express Router for efficient API creation.
Understanding Express Router:
Setting Up Express Router for API Development:
Creating a RESTful API with Express Router:
javascript// app.js
const express = require('express');
const app = express();
const PORT = 3000;
// Importing routes from a separate file
const apiRoutes = require('./routes/api');
// Using the routes defined in the 'api.js' file
app.use('/api', apiRoutes);
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
javascript// routes/api.js
const express = require('express');
const router = express.Router();
// Sample data (in-memory database for demonstration)
let data = [
{ id: 1, name: 'Example 1' },
{ id: 2, name: 'Example 2' }
];
// Endpoint for fetching all data
router.get('/data', (req, res) => {
res.json(data);
});
// Endpoint for fetching a specific item by ID
router.get('/data/:id', (req, res) => {
const id = parseInt(req.params.id);
const item = data.find(item => item.id === id);
if (item) {
res.json(item);
} else {
res.status(404).send('Item not found');
}
});
module.exports = router;
Explanation of the Example:
api.js
file.Advantages of Express Router:
Conclusion: Express Router simplifies API development in Node.js, providing a clean and organized way to manage routes. This modular approach contributes to better code structure and scalability.
Leveraging Express Router streamlines API development, enabling developers to efficiently manage routes and enhance the maintainability of Node.js applications.
Leave a comment