Friday, 5 May 2017

sharing an object between app.js and routes y node.js

This is my app.js

var express = require('express');

...

var model = require('./models/my_model');
var routes = require('./routes/index');

var app = express();

app.use('/', routes);

var middlewareBefore = function(req, res, next){

    my_model.getName(function(err, result){
        if(err){
            console.log(err);
            res.redirect('/error');
        }else{
            console.log(result);
            next();
        }
    })
}

app.use(middlewareBefore);

...

module.exports = app;

and this is my routes/index.js file

var express = require('express');
var router = express.Router();

router.get('/', function(req, res, next) {
    res.render('login', { url: my_model.getUrl() });
});

module.exports = router();

I'm trying to access my_model from the route file. I've already tried using app.locals, res, req, res.locals and app.use('/', routes)(my_model), as seen on different questions from this page, but none of them seem to work... I wonder if the usage of express.Router() is creating this issue (note that setting the middleware before the route didn't solve this)



via amlibtest

No comments:

Post a Comment