在快速应用程序中需要子模块
为什么以下工作?
app.js reports/ ├── index.js └── batch.js
在app.js
:
app.use('/reports', require('./reports')
在index.js
:
var express = require('express'); var batch = require('./batch'); var app = express.createServer(); ... app.use('/batch', batch); module.exports = app;
在batch.js
:
var express = require('express'); module.exports = function() { var app = express.createServer(); console.log('I am here'); app.get('/', function(req, res) { console.log('I am there'); }); return app; };
调用GET /reports/batch
打印I am here
但不打印I am there
任何人都可以指出我的问题?
谢谢
尝试这个:
在app.js中:
var express = require('express'), http = require('http'), path = require('path'); var app = express.createServer(); require('./reports')(app);
在reports / index.js中:
module.exports = function(app){ var batch = require('./batch')(app); app.use('/batch', batch); }
在batch.js中:
module.exports = function(app) { console.log('I am here'); app.get('/', function(req, res) { console.log('I am there'); }); };
请注意,您可能需要根据需要修改app.get路由。 但基本上这里的想法是,而不是一直调用createServer只是不断从一个模块传递到下一个链。
希望这可以帮助!
这是我的app.js. 它将db和app传递给feature.js。 基本上他们共享相同的应用程序variables。
在app.js中
var express = require('express'), http = require('http'), path = require('path'), mongoose = require('mongoose'), db = mongoose.connect('mongodb://abc:123@xxxx.mongohq.com:90000/app123423523'); var app = express(); //here you set app properties require('./routes/feature').with(app, db);
在feature.js中
module.exports.with = function(app, db) { //do work }
似乎我已经忘记了一点点的JavaScript。
我在做
app.use('/batch', batch);
batch
等于
function() { var app = express.createServer(); console.log('I am here'); app.get('/', function(req, res) { console.log('I am there'); }); return app; };
相反,我应该做的
app.use('/batch', batch());
这相当于express.createServer()
返回哪个app.use
期望得到的