在写这篇文章之前,我尝试了Using socket.io in Express 4 and express-generator's /bin/www
的解决方案终端在/routes/messages.js:12
io.on('connection', function(socket){
TypeError: Cannot read property 'on' of undefined
我的文件来了:
/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中/万维网
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('archiers:server');
var http = require('http');
/**
* Get port from environment and 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 all network interfaces.
*/
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
/**
* Normalize a port into a 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 for 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 with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for 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 for 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 your 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 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will 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 to 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;
答案 0 :(得分:2)
你有这段代码:
var messages = require('./routes/messages')(io);
var app = express();
// socket.io
var io = socket();
app.io = io;
你应该在将io变量传递给消息导出函数之前初始化它 - 就像这样:
var app = express();
// socket.io
var io = socket();
app.io = io;
var messages = require('./routes/messages')(io);