Thursday 21 February 2019

Express: mount event: Get the event when the app is mounted


app.on('mount', callback(parent))
‘mount’ event is fired on sub-app, when it is mounted on parent app.

Example
adminApp.on('mount', (parentApp) => {
         console.log(adminApp.locals.name + " is mounted on " + mainApp.locals.name)
})

index.js
var express = require('express')

var mainApp = express()
var adminApp = express()

adminApp.locals.name = "AdminApp"
mainApp.locals.name = "MainApp"

adminApp.on('mount', (parentApp) => {
 console.log(adminApp.locals.name + " is mounted on " + mainApp.locals.name)
})

mainApp.use('/admin', adminApp)

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

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, you can see below messages in console.
AdminApp is mounted on MainApp
Application started in port 3000



Previous                                                 Next                                                 Home

No comments:

Post a Comment