当我尝试在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);
});
});
出了什么问题?
答案 0 :(得分:0)
io.socket.on
应为io.on
。io.socket.emit
应为socket.emit
。如:
io.on('connection', function(socket) {
socket.on('send message', function(data){
socket.emit('new message', data);
);
});