Open In App
Related Articles

Build Your First Router in Node.js with Express

Improve Article
Save Article
Like Article

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.


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.>

Installing Module:

npm install express

Project structure: It will look like the following.

Now we will create all the routes:

Step 1: Inside route folder create Home.js file which will handle ‘/home’ URL.


// Importing express module
const express=require("express")
const router=express.Router()
// Handling request using router
    res.send("This is the homepage request")
// Importing the router

Step 2: Now we will create our second route which will be for login and will handle ‘/login’ URL.


// Importing the module
const express=require("express")
// Creating express Router
const router=express.Router()
// Handling login request
  res.send("This is the login request")

Step 3: Now inside the index.js file we will import all the created routes and use them.


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
    console.log("Server is Running")

Step to run the application: Open the terminal and run index.js using the below command:

node index.js

Output: Open the browser and type localhost:3000 and handle the /home request by the client.

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 06 Oct, 2021
Like Article
Save Article
Similar Reads
Complete Tutorials