Svetan Dimoff Svetan Dimoff - 5 months ago 19
Node.js Question

Cannot import my routes module

When I try to import my routes module into the main app with

app.use(require(./routes))
I get
app.use() requires middleware functions
. How should I go about the
module.exports
function to make it work?

My routes:

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');
});
})();


My main 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);

Answer

You need to return app in your exports function

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));
Comments