Reputation: 1511
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');
}
});
});
Upvotes: 12
Views: 20588
Reputation: 1277
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
});
Upvotes: 36