简体   繁体   中英

how to render common variables from app.js to all routes in express

In my Node.js application some variables that render or every route are common.There are around 4-5 variables which render on every route. And I have around 20 routes.

Currently I am doing passing those variables in every route in res.render

Is there a method by which I can pass these common variables in some place '(eg:app.js)` which is being used by every route, so that I can clean up my code a bit.

I use express.js for node and handlebars for template.

EDIT:I think I should explain a bit more

res.render('abc', {
                        commonitem1: 'one',
                        commonitem2: 'two',
                        ...
                   });

-------------------------------------
another route
res.render('xyz', {
                        commonitem1: 'one',
                        commonitem2: 'two',
                        ...
                   });

I want to avoid this repeating in my every routes and want to render it from a common place.

For session or request dependent values you can store those common values in a global variable and then use them directly in res.render. To do that you have following options

  • Use app.use to store values :

In your app.js add a middleware which does this for you. Remember to write this middleware before any other routes you define because middleware functions are executed sequentially.

app.use(function(req, res, next){
    res.locals.items = "Value";
    next();
});
//your routes follow
app.use(‘/’, home);

In your routes you can place items directly in res.render like:

res.render('layout', {title: 'My awesome title',view: 'home', item :res.locals.items });
  • Use express-session to store values :

If you have express-session installed you can save some data in req.session.item and place them in any route like:

res.render('layout', {title: 'My awesome title',view: 'home', item :req.session.items });

It seems that res.locals is what you are looking for - this object is passed to your views for every request and is scoped to each individual request (ie each request can have its own version of res.locals ). There is also app.locals which is shared for all requests.

I do not have practical experience with this, but you can either use this object to pass all variables to your views or perhaps Express will merge whatever is in app.locals with res.locals and what you send to the view via res.render() . Please test carefully, I have not found relevant information about the merging behaviour in the official docs.

As for populating the res.locals , to keep the code DRY , you can write a custom middleware that populates the object with whatever you need it to have before your actual route logic is executed.

// I created common func for all routes as below.

function commonRes(layout, req, res) {

  if (req.session.user) {
    res.render(layout, {
      user: req.session.user
      //csrfToken: req.csrfToken() // csrf 
    })

  } else {
    res.render(layout, {
      user: null,
      csrfToken: null
    })
  }

  return res.end()
}



// and apply it to all routes simply as below



app.get('/', (req, res) => {

  return commonRes('index.html', req, res)

})

app.get('/new', (req, res) => {

  return commonRes('new.html', req, res)
})

You can create one constants.js file with below code

(function (constants) {
    var FetchDataErrorMessage = "Error while fetching User Data";
    var ConnectionErroMessage = "Error while fetching Connecting Server";
    var InsertDataErrorMessage = "Error while inserting User Data";
    var RemoveDataErrorMessage = "Error while removing User Data";
    var UpdateDataErrorMessage = "Error while updating User Data";
})(module.exports);

In any file where you need to use those variables you can add below code.

var constants = require('constants');    
console.write(constants.RemoveDataErrorMessage);   

Output :- "Error while removing User Data"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM