Access one module from another

Asked

Viewed 60 times

0

Well, I’m learning how to implement MVC with the Express framework, but I came across the following situation in my app.js file:

var express = require('express');
var consign = require('consign');
var bodyParser = require('body-parser');


var app = express();
var router = express.Router();


app.set('view engine', 'ejs');
app.set('views', './app/views');

app.use(express.static('./app/public'));
app.use(bodyParser.urlencoded({extended: true}));

consign()
    .include('app/routes')
    .then('config/dbConnection.js')
    .then('app/models')
    .then('app/controllers')
    .into(app);

module.exports = app;

In my controller, I wanted to have access to this "configuration" without having to import the modules again, mainly using the methods of var router = express.Router();

Is it possible? And what’s the best way to do that?

1 answer

0

One way to do this is to pass the module next to require():

Example:

require('controler')(app)

Ai la on your controller you get it on module.exports and passes to the app the router. I also usually separate the routes of controllers, I think each one does in a way that is my method not that is the best, but it is what suits me best.

module.exports = app => {

...suas rotas aqui...

}

or

router.post()
router.get()
.....

module.exports = app => app.use('/url', router)

I usually do that.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.