最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how to export app object in express? - Stack Overflow

programmeradmin2浏览0评论

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

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

Share Improve this question asked Oct 27, 2016 at 12:51 laoqirenlaoqiren 3,8975 gold badges22 silver badges29 bronze badges 6
  • did you export an object in app.js? – Vinoth Rajendran Commented Oct 27, 2016 at 12:52
  • 2 You have circular dependecies: app.js depends on routes/reg.js, and routes/reg.js depends on app.js. – Freyja Commented Oct 27, 2016 at 12:53
  • yeah, module.exports = app – laoqiren Commented Oct 27, 2016 at 12:53
  • did you require('express')? – Robert Masen Commented Oct 27, 2016 at 12:53
  • yes, I had require it – laoqiren Commented Oct 27, 2016 at 12:54
 |  Show 1 more ment

2 Answers 2

Reset to default 3

You can use request object:

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

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
发布评论

评论列表(0)

  1. 暂无评论