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/users
route.app.get('/users/:userId', (req, res) => {...});
- This creates a route handler for the/users/:userId
route.res.send(
User ${req.params.userId});
- This sends theuserId
parameter passed in the request back as a response.
Helpful links
More of Expressjs
- How do I find Express.js tutorials on YouTube?
- How do I download a zip file using Express.js?
- How do I implement CSRF protection in an Express.js application?
- How do I use adm-zip with Express.js?
- How do I manage user roles in Express.js?
- How can I use Express.js to make an XHR request?
- How do Express.js and Spring Boot compare in terms of features and performance?
- How do I use Yarn to add Express.js to my project?
- How can I disable the X-Powered-By header in Express.js?
- How can I use Express.js with TypeScript?
See more codes...