An Express Router helps organize routes in your web app. It keeps your code clean and easy to manage.
0
0
Creating an Express Router
Introduction
You want to group related routes, like all user-related paths, in one place.
You need to split a large app into smaller parts for easier maintenance.
You want to reuse routes in different parts of your app.
You want to apply middleware only to a specific group of routes.
Syntax
Express
const express = require('express'); const router = express.Router(); router.get('/path', (req, res) => { res.send('Response text'); }); module.exports = router;
Use
express.Router() to create a new router instance.Define routes on the router just like on the main app.
Examples
This example creates a router with a GET route at '/hello' that sends 'Hello World'.
Express
const express = require('express'); const router = express.Router(); router.get('/hello', (req, res) => { res.send('Hello World'); }); module.exports = router;
This router handles a POST request to '/submit' and sends a confirmation message.
Express
const express = require('express'); const router = express.Router(); router.post('/submit', (req, res) => { res.send('Form submitted'); }); module.exports = router;
This router logs every request before handling the '/info' route.
Express
const express = require('express'); const router = express.Router(); router.use((req, res, next) => { console.log('Request received'); next(); }); router.get('/info', (req, res) => { res.send('Info page'); }); module.exports = router;
Sample Program
This program creates an Express app and a router. The router has a GET route at '/greet'. The app uses the router with the prefix '/api', so the full path is '/api/greet'. When you visit that URL, you see the greeting message.
Express
const express = require('express'); const app = express(); const router = express.Router(); // Define a route on the router router.get('/greet', (req, res) => { res.send('Hello from the router!'); }); // Use the router with a prefix app.use('/api', router); // Start the server app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
OutputSuccess
Important Notes
Remember to export your router with module.exports so you can use it in your main app.
Mount routers on paths using app.use('/path', router) to organize routes under that path.
Routers can have their own middleware to handle requests before routes.
Summary
Express Router helps organize routes into smaller, manageable parts.
Create a router with express.Router() and define routes on it.
Use app.use() to mount routers under specific paths.