Reputation: 43
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:
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.
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!
Every advice is much appreciated! :)
Upvotes: 0
Views: 564
Reputation: 46
Only One require statement is required.Remove one of them.
like
const io=require("socket.io");
io.on("conn",function(){
console.log("New Connection");
})
Upvotes: 0
Reputation: 157
You need to pass your server object to the io initializer. 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);
}
Upvotes: 2
Reputation: 3190
You initialized io
incorrectly. Try like this:
var io = socket(http);
Upvotes: 1