laoqiren
laoqiren

Reputation: 3877

how to export app object in express?

I init my app object in app.js:

var app = express();
var reg = require('./routes/reg');
app.use('/reg',reg);
... ...
module.exports = app;

and I call app.get() in reg.js:

var app = require("../app.js");
... ...
app.get("jwtTokenSecret");

my files are like this in the project:

 ---app.js

 ---routes

    ---reg.js

but I found that app is {} in reg.js and the app.get() is not a function, so how to solve it? thanks a lot

Upvotes: 5

Views: 9639

Answers (2)

chasnz
chasnz

Reputation: 179

I agree with stodb-- "use request object". This also works with routes:

app.js

// app.js
const userRoutes = require('./api/routes/user');
app.use('/user', userRoutes);
app.test = 'abc';
module.exports = app;

user.js

// ./api/routes/user.js
router.get('/', (req, res, next) => {
    console.log(req.app.test);
});
// abc

Upvotes: 2

stdob--
stdob--

Reputation: 29172

You can use request object:

// inside reg.js:
console.log( req.app );

Upvotes: 3

Related Questions