- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
router.use() Method in Express.js
The router.use() method has an optional mount path which is set to "/" by default. This method uses the specified middleware functions for this optional mountpath. The method is similar to app.use().
Syntax
router.use( [path], [function, ...] callback )
Example 1
Create a file with the name "routerUse.js" and copy the following code snippet. After creating the file, use the command "node routerUse.js" to run this code as shown in the example below:
// router.use() Method Demo Example // Importing the express module const express = require('express'); // Initializing the express and port number var app = express(); // Initializing the router from express var router = express.Router(); var PORT = 3000; // If the endpoint not found default is called router.use(function (req, res, next) { console.log("Middleware Called"); next(); }) // This method is always invoked router.use(function (req, res, next) { console.log("Welcome to Tutorials Point"); res.send("Welcome to Tutorials Point"); }) app.use('/api', router); app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT); });
Hit the following Endpoint with a GET request − http://localhost:3000/api
Output
C:\home
ode>> node routerUse.js Server listening on PORT 3000 Middleware Called Welcome to Tutorials Point
Example 2
Let's take a look at one more example.
// router.use() Method Demo Example // Importing the express module const express = require('express'); // Initializing the express and port number var app = express(); // Initializing the router from express var router = express.Router(); var PORT = 3000; // All requests will hit this middleware router.use(function (req, res, next) { console.log('Method: %s URL: %s Path: %s', req.method, req.url, req.path) next() }) // this will only be invoked if the path starts with /v1 from the mount point router.use('/v1', function (req, res, next) { console.log("/v1 is called") next() }) // always invoked router.use(function (req, res, next) { res.send('Welcome to Tutorials Point') }) app.use('/api', router) app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT); });
Hit the following Endpoint one by one with a GET request −
- http://localhost:3000/api
- http://localhost:3000/api/v1
Output
C:\home
ode>> node routerUse.js Server listening on PORT 3000 Method: GET URL: / Path: / Method: GET URL: /v1 Path: /v1 /v1 is called
Advertisements