无法调用方法' on'未定义的对象

时间:2015-01-27 20:03:37

标签: javascript node.js socket.io chat

当我尝试在node.js命令提示符下运行节点app.js时,出现错误

cannot call method 'on' of undefined at object

这是我的代码:

var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);

    server.listen(3000);

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

io.socket.on('connection', function(socket) {
socket.on('send message', function(data){
    io.socket.emit('new message', data);
});
});

出了什么问题?

1 个答案:

答案 0 :(得分:0)

  1. io.socket.on应为io.on
  2. io.socket.emit应为socket.emit
  3. 如:

    io.on('connection', function(socket) {
      socket.on('send message', function(data){
        socket.emit('new message', data);
      );
    });