Wednesday 20 February 2019

express: app.locals: Set Application level data


‘app.locals’  is used to set application level data.

Example
app.locals.vendorName = "ABC Corporation"
app.locals.version = "1.2.11"

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

/*Setting Application level data*/
app.locals.vendorName = "ABC Corporation"
app.locals.version = "1.2.11"

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

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

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


Run index.js and hit the url ‘http://localhost:3000/help’, you can see the application details in browser.


You can implement application level statistics using app.locals.
index.js
var express = require('express');
var app = express();

/*Setting Application level data*/
app.locals.vendorName = "ABC Corporation"
app.locals.version = "1.2.11"

/*Variable to track application statistics */
app.locals.homePageCount = 0
app.locals.helpCount = 0
app.locals.statsCount = 0

app.get('/', (req, res) => {
 app.locals.homePageCount++
 res.send('hello world');
});

app.get('/help', (req, res) => {
 app.locals.helpCount++
 res.send(`vendor = ${app.locals.vendorName}<br /> version : ${app.locals.version}`)
})

app.get('/stats', (req, res) => {
 app.locals.statsCount++
 res.send(`homePageCount = ${app.locals.homePageCount} <br />helpPageCount = ${app.locals.helpCount}`)
})

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

Run index.js.

Open home page, help page random number if times.

Open stats page by hitting below url.


You can see the request statistics bases on the your requests to home page and help page.



How to access the local variables from middleware?
From request object, you can access the app.
req.app.locals

Previous                                                 Next                                                 Home

No comments:

Post a Comment