Express.js is a powerful framework for node.js. One of the main advantages of this framework is defining different routes or middleware to handle the client’s different incoming requests. In this article, we will discuss, how to use the router in the express.js server.
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. Multiple requests can be easily differentiated with the help of the Router() function in Express.js.This is the advantage of the use of the Router.
Syntax:
express.Router( [options] )
Parameters: This function accepts one optional parameter whose properties are shown below.
- Case-sensitive: This enables case sensitivity.
- mergeParams: It preserves the request params values from the parent router.
- strict: This enables strict routing.
Return Value: This function returns the New Router Object.
Installing Module: Install the module using the following command.
npm install express
Project structure: It will look like this.

Note: The routes folder contains Home.js and login.js file.
Implementation:
Home.js
const express = require( "express" )
const router = express.Router()
router.get( "/home" , (req,res,next) => {
res.send( "This is the homepage request" )
})
module.exports = router
|
login.js
const express = require( "express" )
const router = express.Router()
router.get( "/login" , (req,res,next) => {
res.send( "This is the login request" )
})
module.exports = router
|
index.js
const express = require( "express" )
const homeroute = require( "./routes/Home.js" )
const loginroute = require( "./routes/login" )
const app = express()
app.use( "/" , homeroute)
app.use( "/" , loginroute)
app.listen((3000), () => {
console.log( "Server is Running" )
})
|
Run index.js using the below command:
node index.js
Output: We will see the following output on the terminal screen.
Server is Running
Now go to http://localhost:3000/login and http://localhost:3000/home, we will see the following output on the browser screen.
