无法导入我的路由模块

时间:2016-06-06 15:44:09

标签: javascript node.js express

当我尝试使用app.use(require(./routes))将路线模块导入主应用时,我得到app.use() requires middleware functions。我应该如何使用module.exports功能才能使其正常工作?

我的路线:

var express = require('express'),
    auth = require('../middleware/auth.js'),
    user = require('../models/user.js'),
    formidable = require('formidable');

module.exports = (function () {
    app.post('/', function (req, res) {
        var form = new formidable.IncomingForm();
        form.parse(req, function (err, fields, files) {
            user.create(fields.username, fields.email, fields.password);
        });
        res.render('./game/game.html', {});
    });

    app.get('/', function (req, res) {
        res.render('./index.html', {});
    });

    app.get('/game', function (req, res) {
        res.render('/views/index.html');
    });
})();

我的主要app.js:

var express = require('express'),
    app = require('express')(),
    cookieSession = require('cookie-session'),
    ejs = require('ejs'),
    path = require('path'),
    cookieParser = require('cookie-parser'),
    util = require('util'),
    port = process.env.PORT || 3000,
    auth = require('./middleware/auth.js'),
    user = require('./models/user.js'),
    formidable = require('formidable');
    router = express.Router();

app.use(express.static(path.join(__dirname, 'public')));
app.set('views', __dirname + '/views');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');

//won't import routes
app.use(require('./routes'));

module.exports = router;

app.listen(port);

3 个答案:

答案 0 :(得分:2)

您需要在导出功能中返回应用

module.exports = function (express) {
  var app  = express.Router();
  app.post('/', function (req, res) {
    var form = new formidable.IncomingForm();
    form.parse(req, function (err, fields, files) {
        user.create(fields.username, fields.email, fields.password);
    });
    res.render('./game/game.html', {});
});

app.get('/', function (req, res) {
    res.render('./index.html', {});
});

app.get('/game', function (req, res) {
    res.render('/views/index.html');
});

 return app

};

...

app.use(require('./routes')(express));

答案 1 :(得分:1)

您的路线必须是Express Router的实例。

var express = require('express');
var router = express.Router();

router.get('/', function(req, res, next) {
    res.send(req.headers);
});

module.exports = router;

现在在app.js中,您可以按照以下方式使用它们:

app.use('/', require('./routes/index'));

答案 2 :(得分:1)

您的模块应该改变您的路由器(app),或者创建自己的路由器并将其导出。

解决方案1 ​​

模块

module.exports = function(app) {
  app.post(...);
  app.get(...);
}

主要应用

require("./routes")(app)

解决方案2

模块

var app = express.Router();
app.post(...);
app.get(...);
module.exports = app;

主要应用

app.use(require("./routes"))

我认为解决方案2更好,因为它避免了变异。