Alex
Alex

Reputation: 1060

Node Express include routes with parameters

I am wanting to use the io instance created inside bin/www inside my routes file.

The www file looks like this

#!/usr/bin/env node
var debug = require('debug')('chat');

var app = require('../app');
var http = require('http').Server(app);
var io = require('socket.io')(http);

var routes = require('../routes/index')(app, io);

app.set('port', process.env.PORT || 3000);

io.sockets.on('connection', routes.chat);

var server = http.listen(app.get('port'), function() {
  debug('Express server listening on port ' + server.address().port);
});

and the routes/index file looks like this

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

router.get('/', function(req, res) {
  res.render('index', { title: 'Express' });
});

module.exports = router;

I am getting this error when trying to start the app

TypeError: Cannot call method 'indexOf' of undefined at Function.proto.handle (c:\node\myapp\node_modules\express\lib\router\index.js:127:28)

Upvotes: 0

Views: 743

Answers (1)

Vadim
Vadim

Reputation: 17957

Your routing module exposes the router. What you probably want is something like this.

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

module.exports = function(app, io) {

   router.get('/', function(req, res) {
     res.render('index', { title: 'Express' });
   });

}

Upvotes: 1

Related Questions