- 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
Express.js – req.baseUrl Property
The req.baseUrl property returns the router instance where this URL path is mounted. This property is similar to the mountpath property of the app object, except for the difference that app.mountpath returns the matched path patterns.
Syntax
req.baseUrl
Example 1
Create a file with the name "reqBaseUrl.js" and copy the following code snippet. After creating the file, use the command "node reqBaseUrl.js" to run this code as shown in the example below −
// req.baseUrl Property Demo Example // Importing the express var express = require('express'); // Initializing the express and port number var app = express(); // Initializing the router from express var router = express.Router(); var PORT = 3000; // Defining an Endpoint router.get('/api', function (req, res) { console.log(req.baseUrl); res.end(); }) app.use('/v1', router); app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT); });
Output
Hit the following Endpoint with a GET request: localhost:3000/v1/api
C:\home
ode>> node reqBaseUrl.js Server listening on PORT 3000 /v1
Example 2
Let's take a look at one more example.
// req.baseUrl Property Demo Example // Importing the express var express = require('express'); // Initializing the express and port number var app = express(); // Initializing the router from express var router = express.Router(); var PORT = 3000; app.use('/employee', router); // Defining an endpoint router.get('/login', function (req, res) { if(req.baseUrl == '/employee') { console.log("Show Login Page"); res.end(); } else { console.log("Invalid Route") res.send("Invalid Route") } }) app.use('/v1', router); app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT); });
Output
Hit the following Endpoint with a GET Request: localhost:3000/employee/login
C:\home
ode>> node reqBaseUrl.js Server listening on PORT 3000 Show Login Page
Advertisements