[英]Cannot read property 'on' of undefined? -> ERROR
So I'm creating a web app and while building the server part I got stuck because of an error in the CMD that says: 因此,我正在创建一个Web应用程序,并且在构建服务器部件时由于CMD中的错误而卡住了,原因是:
TypeError: Cannot read property 'on' of undefined
I tried to make the connection between the server.js and client.js but it seems not to work even though I've included all the needed modules. 我试图在server.js和client.js之间建立连接,但是即使我包含了所有必需的模块,它似乎也不起作用。
var fs = require('fs'); // required for file serving
var http = require('http');
var express = require('express');
var app = express();
var socket = require('socket.io');
var io = require('socket.io');
// loading all HTMl files
// loading CSS, JS, Pictues
// for the HTML index
// server.listen
// !!! HERE IS THE PROBLEM !!!
io.sockets.on('connection', newConnection);
function newConnection(socket){
console.log('new connection');
console.log(socket);
}
I want my server.js to contact with the client.js (there's nothing written in it) and run as a normal server! 我希望我的server.js与client.js(没有任何内容)联系并作为普通服务器运行!
Every advice is much appreciated! 每个建议都非常感谢! :) :)
You need to pass your server object to the io initializer. 您需要将服务器对象传递给io初始化程序。 The following code might help: 以下代码可能会有所帮助:
var fs = require('fs'); // required for file serving
var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var port = process.env.PORT || 8080;
server.listen(port);
io.sockets.on('connection', newConnection);
function newConnection(socket){
console.log('new connection');
console.log(socket);
}
You initialized io
incorrectly. 您未正确初始化io
。 Try like this: 尝试这样:
var io = socket(http);
Only One require statement is required.Remove one of them. 只需要一个require语句。删除其中之一。
like 喜欢
const io=require("socket.io");
io.on("conn",function(){
console.log("New Connection");
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.