Express res.locals Property

RMAG news

The res.locals property is an object that holds response local variables specific to the current request. It has a scope limited to the request and is accessible only to the view(s) rendered during that particular request/response cycle, if any.

Basically if you have to pass many local variables to the rendering page then you can store all of them as res.locals object

See the code below/////////////

const express = require(‘express’);
const app = express();
const PORT = 3000;

app.get(‘/’,function (req, res) {

// Sending multiples locals

res.locals.name = ‘sid’;

res.locals.age = 21;

res.locals.gender = ‘Male’

console.log(res.locals);

res.end();

});

app.listen(PORT,function (err) {

if (err) console.log(err);

console.log(
“Server listening on
PORT”,PORT );

});

Leave a Reply

Your email address will not be published. Required fields are marked *