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');
}
});
});
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.
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.
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With