Skip to content
Related Articles

Related Articles

Improve Article

How to filter path of routes in Express.js ?

  • Last Updated : 28 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. In this article, we will be discussing how to filter the paths of routes using the express.js in node.js.

The app.use() method is used to handle different to filter the request for particular routes in node.js This function is used to mount the specified middleware function(s) at the path which is being specified. It is mostly used to set up middleware for your application.

Syntax:

app.use(path, callback)

Parameters: This method takes the following two parameters:

  • path: It is the path for which the middleware function is being called. It can be a string representing a path or path pattern or a regular expression pattern to match the paths.
  • callback: It is a middleware function or a series/array of middleware functions.

 



Installing Module: Install the required module using the following command.

npm install express

Project structure: It will look like this.

Note: Home.js and login.js files are present in the routes folder.

Home.js




// Importing express module
const express = require("express")
const router = express.Router()
  
// Handling request using router
router.get("/home", (req, res, next) => {
    res.send("This is the homepage request")
})
  
// Exporting 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("/login", (req, res, next) => {
  res.send("This is the login request")
})
  
// Exporting the router
module.exports = router

index.js




// Requiring module
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()
  
// Filtering the routes path
app.use("/", homeroute)
app.use("/", loginroute)
  
// Server setup
app.listen((3000), () => {
    console.log("Server is Running")
})

Run index.js file using below command:

node index.js

Output: Now open your browser and go to http://localhost:3000/home, you will see the following output:




My Personal Notes arrow_drop_up
Recommended Articles
Page :