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 set the time zone in Express.js?
- How can I use Axios with Express.js?
- How do I use Express.js to handle x-www-form-urlencoded data?
- How can I render HTML pages using Express.js?
- How can I use express-zip js to zip and download files?
- How do I use Zod with Express.js?
- How can I use Server-Sent Events (SSE) with Express.js?
- How can I use Express.js to generate a zip response?
- How can I use Express.js to yield results?
See more codes...