在我使用 socket.io 的程序中,特定事件不起作用。其余的工作正常。这是问题发生的地方:
第一个 html 文件:
socket.on('connect', () => {socket.emit('phone', 'phone');});
服务器文件:
io.on('connection', function(socket){
io.on('phone', function(socket, data){
io.emit('stuurbedrijfsnaam', 'stuurbedrijfsnaam');
});
});
第二个 html 文件:
socket.on('stuurbedrijfsnaam', function(socket){
socket.emit('stuurbedrijfsnaam',bedrijfsnaam)
})
这是控制台中给出的完整错误:
index.js:83 Uncaught TypeError: Cannot read property 'apply' of undefined
at r.emit (index.js:83)
at r.onevent (index.js:83)
at r.onpacket (index.js:83)
at r.<anonymous> (index.js:83)
at r.emit (index.js:83)
at r.ondecoded (index.js:83)
at a.<anonymous> (index.js:83)
at a.r.emit (index.js:83)
at a.add (index.js:83)
at r.ondata (index.js:83)
at r.<anonymous> (index.js:83)
at r.emit (index.js:83)
at r.onPacket (index.js:83)
at r.<anonymous> (index.js:83)
at r.emit (index.js:83)
at r.onPacket (index.js:83)
at r.onData (index.js:83)
at WebSocket.ws.onmessage (index.js:83)
它引用了 index.js:83,它位于 socket.io 本身创建的文件夹中。有第81、82、83行:
Backoff.prototype.setJitter = function(jitter){
this.jitter = jitter;
};
希望我提供了足够的资源。如果有人帮助我,那就太好了。谢谢!
最佳答案
此错误的原因是您试图通过自定义事件处理程序的 socket
参数调用 .emit()
,which is incorrect usage根据 socket.io 客户端 API 的文档。
考虑修改您的客户端代码,如下所示,从您的处理程序中删除 socket
参数,以便在实际的套接字实例上调用 .emit()
:
socket.on('stuurbedrijfsnaam', function(){ // remove 'socket' here
// cause emit() to be called on actual socket instance
socket.emit('stuurbedrijfsnaam',bedrijfsnaam)
})
在您的第一个 html 文件中 socket.emit('phone', 'phone');
的原因是 emit()
在原始套接字实例上被调用,而不是通过 socket
参数传递给事件处理程序,就像您在秒 html 文件中所做的那样。
希望对您有所帮助!
关于javascript - Socket.io 未捕获类型错误 : Cannot read property 'apply' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53311432/