Express.js – app.mountpath Property


The app.mountpath property contains those path patterns on which a sub-app was mounted. A sub-app can be defined as an instance of Express that may be used for handling the request to a route.

This property is similar to the baseUrl property of the req object; the only difference is that req.baseUrl returns the matched URL path instead of the matched patterns.

Syntax

app.mountpath

Example 1

Create a file "appMountpath.js" and copy the following code snippet. After creating the file, use the command "node appMountpath" to run this code.

// app.mountpath code Demo Example

// Importing the express module
var express = require('express');

// Initializing the express and port number
var app = express();
var user = express(); // this is a subapp
var PORT = 3000;

// Defining an endpoint
user.get('/', function (req, res) {

   // printing the mounted path
   console.log(user.mountpath);
   res.send('This is the user homepage');
   console.log('This is the user homepage');
});

// Mounting the subapp over our mai app
app.use('/user', user); // Mounting the sub app
app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

Output

C:\home
ode>> node appMountpath.js Server listening on PORT 3000 /user This is the user homepage

Example 2

Let’s take a look at one more example.

// app.mountpath code Demo Example

// Importing the express module
var express = require('express');

// Initializing the express and port number
var app = express();
var PORT = 3000;

// Defining an endpoint
app.get('/', function (req, res) {
   console.log("Endpoint is: ",app.mountpath)
   res.send("Welcome to Tutorials Point")
   console.log("Welcome to Tutorials Point")
});

app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

Output

C:\home
ode>> node appMountpath.js Server listening on PORT 3000 Endpoint is: / Welcome to Tutorials Point

Updated on: 30-Sep-2021

302 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements