Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express.js - How to Modify app.locals variables in routes

I have a node.js project. The following code is part of my app.js file. I'm making a query from the database and storing the results in a global variabled called 'Cats'. I'm using this variable to display the categories on a sidebar of the site. I don't think its relevant but I am using Jade as templating engine.

var app = express()

var query = "SELECT * FROM findadoc.categories";
client.execute(query, [], function(err, results) {
  if(err) {
    res.status(404).send({meg: err});
  }
  else {
    app.locals.cats = results.rows;
  }
});

In one of the routes, I allow the user to add additional category to the database. What I need is for the 'apps.locals.cats' variable to get updated with the new set of categories. Is there anyway for me to modify this in my routes? I tried the following but it didn't work.

router.post('/add', function(req, res, next) {
    var cat_id = cassandra.types.uuid();
    var query = "INSERT INTO findadoc.categories(cat_id, name) VALUES (?,?)";
    client.execute(query, [cat_id, req.body.name], {prepare: true},   function(err, results) {
        if(err) {
            res.status(404).send({msg: err});
        } 
        else {
            cats = results.rows;
            req.flash('success', "Category Added");
            res.location('/doctors');
            res.redirect('/doctors');
        }
    });
});
like image 264
Sohrab Hejazi Avatar asked Jul 26 '15 07:07

Sohrab Hejazi


People also ask

What is RES locals in Express?

The res. locals is an object that contains the local variables for the response which are scoped to the request only and therefore just available for the views rendered during that request or response cycle.

How the dynamic routing is working in ExpressJS?

ExpressJS Online Training We can now define routes, but those are static or fixed. To use the dynamic routes, we SHOULD provide different types of routes. Using dynamic routes allows us to pass parameters and process based on them. var express = require('express'); var app = express(); app.


1 Answers

In Express 4 You can access to app from req with req.app. See Request object API doc.

Locals are available in middleware via req.app.locals (see req.app)

In your middleware you could do it as this:

router.post('/add', function(req, res, next) {
    // do some cool stuff
    req.app.locals.cats = something;
    // more cool stuff
});
like image 69
Carlos Avatar answered Sep 22 '22 01:09

Carlos