Reputation: 113
I am developing a node app using express which has a chatting system and I am using socket.io but I get this error
Server is listening on 3000
made socket connection
C:\Users\User\MyFolder\Projects\FMIS\app\app.js:139
socket.on('chat', function(data){
^
TypeError: socket.on is not a function
at Namespace.<anonymous>
(C:\Users\User\MyFolder\Projects\FMIS\app\app.js:139:12)
at emitOne (events.js:116:13)
at Namespace.emit (events.js:211:7)
at Namespace.emit
at _combinedTickCallback (internal/process/next_tick.js:131:7)
at process._tickCallback (internal/process/next_tick.js:180:9)
This what I have tried to do in my `app.js
var reload = require('reload');
var bodyParser = require('body-parser');
var app = express();
var socket = require('socket.io');
app.set('port', process.env.PORT || 3000);
app.set('view engine', 'ejs');
app.set('views','app/views');
app.locals.siteTitle = "FMIS";
app.use(express.static('app/public'));
app.use(require('./routes/Chat_api'));
app.use(require('./routes/Chat'));
var server = app.listen(app.get('port'),()=>{
console.log('Server is listening on '+ app.get('port'));
});
var io = socket(server);
io.on('connection',function(){
console.log('made socket connection');
socket.on('chat', function(data){
// io.sockets.emit('chat',data);
console.log(data);
});
});
reload(server, app);
I send and recieve data from the client like this
socket.emit('chat',{
user: chatUsername.value,
Message: chatMessage.value
});
socket.on('chat',function(data){
// showMessage(data);
console.log(data);
});
Upvotes: 4
Views: 19355
Reputation: 1
for me it was that i'm using socket.current in my main app so , it didnt recognized socket.on but socket.current.on instead
Upvotes: 0
Reputation: 142
You're using the library reference for socket.io, which does not contain the function property on
. What are you trying to do is use the socket provided to you as an argument of the callback on io.on
connection event. To fix that you can just add socket
to the arguments on your callback function. Like this:
io.on('connection',function(socket) {
console.log('made socket connection');
socket.on('chat', function(data){
// io.sockets.emit('chat',data);
console.log(data);
});
});
Now socket
is referring to the socket provided to you by the connection. See this example for more info.
Upvotes: 5