How do you handle nested routes in Express.js?
Last Updated :
21 Nov, 2023
In this article we are going to learn that how can we setup nested routes in Express JS. Nested routes are the routes that are defined within other routes. This is used to organize your code.
We are going to implement the nested routes using the below given two approaches.
Using Express JS
We are going to create nested routes by using Express JS only, in which we will create nested routes with HTTP methods only, and we do not need to use any other module in it.
Syntax:
app.get('base URL',()=>{})
app.get('base URL/Nested URL',()=>{})
Example: Implementation of above approach.
Javascript
const express = require( 'express' );
const app = express();
const PORT = 3000;
app.use(express.json());
app.get( "/" , (req, res) => {
console.log( "GET Request Successfull!" );
res.send( "Get Req Successfully initiated" );
})
app.get( "/user" , (req, res) => {
res.send(`Client is requesting for USER Data`)
})
app.get( "/user/:id" , (req, res) => {
res.send(`Client required ID -> ${req.params.id}`)
})
app.listen(PORT, () => {
console.log(`Server established at ${PORT}`);
})
|
Output:
Using Express JS Router
Through the Express JS Router, we will create a base URL, and then we can directly use the router to implement a nested URL through it. The express.Router() function is used to create a new router object. This function is used when you want to create a new router object in your program to handle requests.
Syntax:
express.Router( [options] )
Example: This example implements nested routing using Express JS Router
Javascript
const express = require( 'express' );
const app = express();
const PORT = 3000;
const router = express.Router();
router.get( '/' , (req, res) => {
res.send( "USER NESTED API IS Endpoint!" );
})
router.get( '/api' , (req, res) => {
res.send( "/API endpoint" )
})
app.use( '/user' , router);
app.listen(PORT, () => {
console.log(`Server established at ${PORT}`);
})
|
Output:
Share your thoughts in the comments
Please Login to comment...