expressjsHow can I create nested routes in Express.js?
Nested routes are routes that are nested within other routes in Express.js. This allows us to create a hierarchical structure for our routes. Here is an example of how to create nested routes in Express.js:
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.get('/users', (req, res) => {
res.send('Users page');
});
app.get('/users/:userId', (req, res) => {
res.send(`User ${req.params.userId}`);
});
app.listen(3000);
This example code will create 3 routes: /, /users and /users/:userId. The /users/:userId route is nested within the /users route. When a request is made for /users/:userId, the :userId parameter will be passed to the route handler.
Code explanation
const express = require('express');- This imports the Express.js module.const app = express();- This creates an Express.js application.app.get('/', (req, res) => {...});- This creates a route handler for the/route.app.get('/users', (req, res) => {...});- This creates a route handler for the/usersroute.app.get('/users/:userId', (req, res) => {...});- This creates a route handler for the/users/:userIdroute.res.send(User ${req.params.userId});- This sends theuserIdparameter passed in the request back as a response.
Helpful links
More of Expressjs
- How do I download a zip file using Express.js?
- How do I use Express.js to parse YAML files?
- How can I make an XHR request using Express.js?
- How do I implement CSRF protection in an Express.js application?
- How can I disable the X-Powered-By header in Express.js?
- How can I set up X-Frame-Options in ExpressJS?
- How do I use Yarn to add Express.js to my project?
- How do I use Zod with Express.js?
- How can I use the x-forwarded-for header in Express.js?
- How do I use an Express.js logger?
See more codes...