Coder746584 Coder746584 - 6 months ago 54
Node.js Question

Easiest way to pass variables to routes templates in Express?

I've just made an Node.js app modular by splitting up data models and routes into separate files.

My routes are exported by

express.Router()
. In these routes I would like to import queried values from my app.js to be rendered with the templates.

How would I in the easiest way save things lets say with app.locals or req.variableName?

Since the route using
express.Router()
ties it together with app.js, should I be using
app.params()
and somehow make these values accessible?

Using globals seems like a worse idea as I'm scaling up the app. I'm not sure if best practice would be saving values to the process environment either using
app.locals.valueKey = key.someValue
...

Big thanks in advance to anyone

Answer

If I understand the question correctly, you want to pass a value to a later middleware:

app.js:

// Let's say it's like this in this example

var express = require('express');
var app = express();

app.use(function (req, res, next) {
    var user = User.findOne({ email: 'someValue' }, function (err, user) {
        // Returning a document with the keys I'm interested in
        req.user = { key1: value1, key2: value2... }; // add the user to the request object
        next(); // tell express to execute the next middleware
    });
});

// Here I include the route
require('./routes/public.js')(app); // I would recommend passing in the app object

/routes/public.js:

module.export = function(app) {
    app.get('/', function(req, res) {
        // Serving Home Page (where I want to pass in the values)
        router.get('/', function (req, res) {
            // Passing in the values for Swig to render
            var user = req.user; // this is the object you set in the earlier middleware (in app.js)
            res.render('index.html', { pagename: user.key2, ... });
        });
    });
});