Saturday, 9 March 2019

Express: res.locals: Set response local variables


res.locals
This property is used to set response local variables.

index.js
'use strict'

const express = require('express')

const app = express()

app.get('/', (req, res) => {
 res.send('Hello World')
})

app.use('/welcome', (req, res, next) => {
 console.log('Logging the request')
 res.locals.isLoggingDone = true
 next()
})

app.use('/welcome', (req, res, next) => {
 console.log('Authorizing the request')
 res.locals.isAuthorizationDone = true
 next()
})

app.get('/welcome', (req, res) => {
 var logging = res.locals.isLoggingDone
 var authorization = res.locals.isAuthorizationDone
 
 console.log('Is request logged : ' + logging)
 console.log('Is request authorized : ' + authorization)
 
 res.send('Dear User, Good Morning!!!!!!!')
})

const port = 3000
app.listen(port, () => console.log(`Application started listening on port ${port}!`));

Run index.js

Open the url ‘http://localhost:3000/welcome’ in browser, you will see below messages in console.

Logging the request
Authorizing the request
Is request logged : true
Is request authorized : true



Previous                                                 Next                                                 Home

No comments:

Post a Comment