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 set the time zone in Express.js?
- How can I use Express.js to enable HTTP/2 support?
- How can I use Express.js to generate a zip response?
- How do I use Express.js to parse YAML files?
- How can I set up X-Frame-Options in ExpressJS?
- How can I use the x-forwarded-for header in Express.js?
- How do I set up a YAML configuration file for a Node.js Express application?
- How do Express.js and Spring Boot compare in terms of features and performance?
- How can I use Express.js to create a query?
See more codes...