How to use Express JS Router In Express
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
// Server.js const express = require( 'express' ); const app = express(); const PORT = 3000; const router = express.Router(); // Nested Route router.get( '/' , (req, res) => { res.send( "USER NESTED API IS Endpoint!" ); }) // Another Nested Route router.get( '/api' , (req, res) => { res.send( "/API endpoint" ) }) // Parent Route app.use( '/user' , router); app.listen(PORT, () => { console.log(`Server established at ${PORT}`); }) |
Output:
How do you handle nested routes in Express.js?
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.
Table of Content
- Using Express JS
- Using Express JS Router
Contact Us