Socket.io和Express得到一个错误“没有方法套接字”

这里是我试图testing一个基本的Socket.io和Express设置(每个在socket.io网站上的例子)时得到的错误:

/Users/scottcorgan/Projects/sevenly/campaigns/node_modules/socket.io/lib/manager.js:659 var socket = this.namespaces[i].socket(data.id, true); ^ TypeError: Object function extend(another) { var properties = Object.keys(another); var object = this; properties.forEach(function (property) { object[property] = another[property]; }); return object; } has no method 'socket' at Manager.handleClient (/Users/scottcorgan/Projects/sevenly/campaigns/node_modules/socket.io/lib/manager.js:659:41) at Manager.handleUpgrade (/Users/scottcorgan/Projects/sevenly/campaigns/node_modules/socket.io/lib/manager.js:588:8) at HTTPServer.<anonymous> (/Users/scottcorgan/Projects/sevenly/campaigns/node_modules/socket.io/lib/manager.js:119:10) at HTTPServer.emit (events.js:88:20) at Socket.<anonymous> (http.js:1390:14) at TCP.onread (net.js:334:27) 

欣赏我可以得到的任何帮助,请:)

这个问题源于您或您使用的库正在向Object.prototype添加函数。

因此这个代码:

 Object.prototype.foo = function() {}; Object.prototype.bar = function() {}; var myObj = { x: 1 }; for (var i in myObj) { console.log(i) } 

将打印: x,foo,bar (不一定按照这个顺序),而不仅仅是你所期望的。

在你的情况下,这发生在manager.js中:

 // initialize the socket for all namespaces for (var i in this.namespaces) { var socket = this.namespaces[i].socket(data.id, true); // echo back connect packet and fire connection event if (i === '') { this.namespaces[i].handlePacket(data.id, { type: 'connect' }); } } 

这个代码并不期望遇到声明的: extend键,正如您从错误的堆栈跟踪中看到的那样:

 TypeError: Object function extend(another) { var properties = Object.keys(another); var object = this; properties.forEach(function (property) { object[property] = another[property]; }); return object; } has no method 'socket' 

该程序实际上是试图调用扩展函数上的socket()

看到鲍勃在这里咆哮关于添加function到Object.prototype

至于解决scheme,你可以像这样在manager.js中添加一个条件语句:

 // initialize the socket for all namespaces for (var i in this.namespaces) { if ('extend' == i) continue; // ADDED var socket = this.namespaces[i].socket(data.id, true); // echo back connect packet and fire connection event if (i === '') { this.namespaces[i].handlePacket(data.id, { type: 'connect' }); } } 

或者你可以删除Object.prototype.extend = function(…){}声明,这是我个人的偏好。

你的this.namespaces[i].socket(data.id, true); 不存在。 做类似console.log(typeof this.namespaces[i].socket(data.id, true)); 你可能会得到一个undefined

我敢打赌,您的命名空间数组中的一个元素缺失。