在快递应用中需要子模块

时间:2013-12-01 20:25:03

标签: node.js express

为什么以下不起作用?

  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

有人能指出我的问题吗?

由于

3 个答案:

答案 0 :(得分:2)

试试这个:

app.js中的

var express = require('express'),
    http = require('http'),
    path = require('path');

var app = express.createServer();

require('./reports')(app);
报告/ 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,只是不断地将它从一个模块传递到下一个模块。

希望这有帮助!

答案 1 :(得分:0)

这是我的app.js.它将db和app传递给feature.js。基本上他们共享相同的app变量。

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
    }

答案 2 :(得分:0)

似乎我已经忘记了一点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期望得到的内容