Skip to content
Related Articles

Related Articles

Improve Article

How to create multiple routes in the same express.js server ?

  • Last Updated : 30 Jun, 2021

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. Express. js allows us to create multiple routes on a single express server. Creating multiple routes on a single server is better to practice rather than creating single routes for handling different requests made by the client. In this article, we will discuss how to create multiple routes on a single express 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] )

Optional Parameters:

  • Case-sensitive: This enables case sensitivity.
  • mergeParams: It preserves the req. params values from the parent router.
  • strict: This enables strict routing.

Return Value: This function returns the New Router Object.



Structure Model :

Installing Module:

npm install express

Project structure:

Routes:

Home.js




// Importing express module
const express=require("express")
const router=express.Router()
  
// Handling request using router
router.get("/",(req,res,next)=>{
    res.send("This is the homepage request")
})
  
// Importing the router
module.exports=router

login.js




// Importing the module
const express=require("express")
  
// Creating express Router
const router=express.Router()
  
// Handling login request
router.get("/",(req,res,next)=>{
    res.send("This is the login request")
})
module.exports=router

Index.js




const express=require("express")
  
// Importing all the routes
const homeroute=require("./routes/Home.js")
const loginroute=require("./routes/login")
  
// Creating express server
const app=express()
  
// Handling routes request
app.use("/home",homeroute)
app.use("/login",loginroute)
app.listen((3000),()=>{
    console.log("Server is Running")
})

Run index.js using the below command:

node index.js

Output: Handling the /home request by the client.




My Personal Notes arrow_drop_up
Recommended Articles
Page :