node.js - socket.io with express generator -
before write tried solution @ using socket.io in express 4 , express-generator's /bin/www
the terminal show error on /routes/messages.js:12
io.on('connection', function(socket){ typeerror: cannot read property 'on' of undefined
here comes files:
/routes/messages.js
var express = require('express'); var controller = require('../controllers/messagecontroller'); var passport = require('passport'); var router = express.router(); router.get('/', controller.plain); module.exports = function(io){ var router = express.router(); io.on('connection', function(socket){ console.log('**********************************************************'); console.log('mensaje desde socket.io en el archivo de rutas messages.js'); console.log('**********************************************************'); }); return router; };
/bin/www
#!/usr/bin/env node /** * module dependencies. */ var app = require('../app'); var debug = require('debug')('archiers:server'); var http = require('http'); /** * port environment , store in express. */ var port = normalizeport(process.env.port || '3000'); app.set('port', port); /** * create http server. */ var server = http.createserver(app); // socket.io var io = app.io; io.attach(server); /** * listen on provided port, on network interfaces. */ server.listen(port); server.on('error', onerror); server.on('listening', onlistening); /** * normalize port number, string, or false. */ function normalizeport(val) { var port = parseint(val, 10); if (isnan(port)) { // named pipe return val; } if (port >= 0) { // port number return port; } return false; } /** * event listener http server "error" event. */ function onerror(error) { if (error.syscall !== 'listen') { throw error; } var bind = typeof port === 'string' ? 'pipe ' + port : 'port ' + port; // handle specific listen errors friendly messages switch (error.code) { case 'eacces': console.error(bind + ' requires elevated privileges'); process.exit(1); break; case 'eaddrinuse': console.error(bind + ' in use'); process.exit(1); break; default: throw error; } } /** * event listener http server "listening" event. */ function onlistening() { var addr = server.address(); var bind = typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr.port; debug('listening on ' + bind); }
/app.js
var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieparser = require('cookie-parser'); var bodyparser = require('body-parser'); var morgan = require('morgan'); var mongoose = require('mongoose'); var passport = require('passport'); var localstrategy = require('passport-local').strategy; var session = require('express-session'); var socket = require('socket.io'); // var routes var index = require('./routes/index'); var users = require('./routes/users'); var projects = require('./routes/projects'); var messages = require('./routes/messages')(io); var app = express(); // socket.io var io = socket(); app.io = io; io.on( "connection", function( socket ) { console.log( "a user connected" ); }); // para devolver estado por consola. app.use(morgan('combined')); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); var account = require('./models/accounts'); passport.use(new localstrategy(account.authenticate())); passport.serializeuser(account.serializeuser()); passport.deserializeuser(account.deserializeuser()); // uncomment after placing favicon in /public //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); app.use(logger('dev')); app.use(bodyparser.json()); app.use(bodyparser.urlencoded({ extended: false })); app.use(cookieparser()); //app.use(multer({dest : "./userfiles/projectimage"})) app.use(express.static(path.join(__dirname, 'public'))); app.use(require('express-session')({ secret: 'secretpass', resave: true, saveuninitialized: true, cookie: { maxage : 3600000 } //1 hour })); app.use(passport.initialize()); app.use(passport.session()); //rutas express app.use('/', index); app.use('/user', users); app.use('/project', projects); app.use('/message', messages) // catch 404 , forward error handler app.use(function(req, res, next) { var err = new error('not found'); err.status = 404; next(err); }); // error handlers // development error handler // print stacktrace if (app.get('env') === 'development') { app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } // production error handler // no stacktraces leaked user app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); mongoose.connect('mongodb://localhost/db'); module.exports = app;
in app.js have code:
var messages = require('./routes/messages')(io); var app = express(); // socket.io var io = socket(); app.io = io;
you should initialize io variable before passing messages export function - so:
var app = express(); // socket.io var io = socket(); app.io = io; var messages = require('./routes/messages')(io);
Comments
Post a Comment