Tuesday 5 March 2019

Express: req.app: Get the reference of express application


‘req.app’ refers to the express application.

Example
var response = `vendorname : ${req.app.locals.vendorName} <br />
         version : ${req.app.locals.version} <br />
         maintenanceSupported : ${req.app.locals.maintenanceSupported}`

As you see above snippet, I am access the application specific properties using ‘req.app’ object.

index.js
//Load express module
const express = require('express')

//Put new Express application inside app variable
const app = express()

/*Set some variables at application level*/
app.locals.vendorName = "ABC Corporation"
app.locals.version = "1.2.32"
app.locals.maintenanceSupported = true

const port = 3000

//When user hits the home page, then the message prints in browser.
app.get('/', (req, res) => res.send('Welcome to Node.js Programming'))

app.get('/help', (req, res) => {
 var response = `vendorname : ${req.app.locals.vendorName} <br />
 version : ${req.app.locals.version} <br />
 maintenanceSupported : ${req.app.locals.maintenanceSupported}`
 
 res.send(response)
})


// Start the express application on port 8080 and print server start message to console.
app.listen(port, () => console.log(`Application started listening on port ${port}!`));

Run index.js.


Open the url ‘http://localhost:3000/help’ in browser, you can see below message.



Previous                                                 Next                                                 Home

No comments:

Post a Comment