Thursday 21 February 2019

app.mountPath: Gives the patterns on which this sub app is mounted


‘app.mountPath’ contains one or more path patterns on which a sub-app was mounted.

index.js
var express = require('express')
var mainApp = express()
var adminApp = express()
var userApp = express()

mainApp.use('/user', userApp)
mainApp.use('/admin', adminApp)

mainApp.get('/', (req, res) => {
 res.send('hello world')
});

userApp.get('/help', (req, res) => {
 console.log("User mount path : " + userApp.mountpath);
 res.send("User requested for help information")
})

userApp.get('/', (req, res) => {
 console.log("User mount path : " + userApp.mountpath);
 res.send("User home page")
})

adminApp.get('/', (req, res) => {
 console.log("Admin mount path : " + adminApp.mountpath);
 res.send("Admin home page")
})

adminApp.get('/stats', (req, res) => {
 console.log("Admin mount path : " + adminApp.mountpath);
 res.send("Admin requested for statistics")
})

mainApp.listen(3000, () => {console.log("Application started in port 3000")});

Run the application index.js.

Open below url in browser.

You can see below message in console.
Admin mount path : /admin

Open below url in browser.
localhost:3000/user

You can see below messages in console.
User mount path : /user

You can even mount multiple path patterns.  If a sub-app is mounted on multiple path patterns, app.mountpath returns the list of patterns it is mounted on.

Example
mainApp.use(['/admin', '/manager'], adminApp)


index.js
var express = require('express')
var mainApp = express()
var adminApp = express()
var userApp = express()

mainApp.use('/user', userApp)
mainApp.use(['/admin', '/manager'], adminApp)

mainApp.get('/', (req, res) => {
 res.send('hello world')
});

userApp.get('/help', (req, res) => {
 console.log("User mount path : " + userApp.mountpath);
 res.send("User requested for help information")
})

userApp.get('/', (req, res) => {
 console.log("User mount path : " + userApp.mountpath);
 res.send("User home page")
})

adminApp.get('/', (req, res) => {
 console.log("Admin mount path : " + adminApp.mountpath);
 res.send("Admin home page")
})

adminApp.get('/stats', (req, res) => {
 console.log("Admin mount path : " + adminApp.mountpath);
 res.send("Admin requested for statistics")
})

mainApp.listen(3000, () => {console.log("Application started in port 3000")});

Run index.js

Open below url in browser.

You can see below messages in console.
Admin mount path : /admin,/manager



Previous                                                 Next                                                 Home

No comments:

Post a Comment