Advanced Node and Express - Handle a Disconnect (server not handling disconnect)

It says I’m not handling the disconnect on the server side even though it looks like I am. Is there anything wrong with my disconnect response?

Error:

expected '\'use strict\';\n\nconst express     = require(\'express\');\nconst session     = require(\'express-session\');\nconst bodyParser  = require(\'body-parser\');\nconst fccTesting  = require(\'./freeCodeCamp/fcctesting.js\');\nconst auth        = require(\'./app/auth.js\');\nconst routes      = require(\'./app/routes.js\');\nconst mongo       = require(\'mongodb\').MongoClient;\nconst passport    = require(\'passport\');\nconst cookieParser= require(\'cookie-parser\')\nconst app         = express();\nconst http        = require(\'http\').Server(app);\nconst sessionStore= new session.MemoryStore();\nrequire(\'dotenv\').config()\nconst cors        = require(\'cors\');\nconst io = require(\'socket.io\')(http);\n\napp.use(cors());\n\nfccTesting(app); //For FCC testing purposes\n\napp.use(\'/public\', express.static(process.cwd() + \'/public\'));\napp.use(cookieParser());\napp.use(bodyParser.json());\napp.use(bodyParser.urlencoded({ extended: true }));\napp.set(\'view engine\', \'pug\')\nvar currentUsers = 0;\n\n\n\napp.use(session({\n  secret: process.env.SESSION_SECRET,\n  resave: true,\n  saveUninitialized: true,\n  key: \'express.sid\',\n  store: sessionStore,\n}));\n\n\nmongo.connect(process.env.DATABASE, (err, db) => {\n    if(err) console.log(\'Database error: \' + err);\n  \n    auth(app, db);\n    routes(app, db);\n      \n    http.listen(process.env.PORT || 3000);\n\n  \n    //start socket.io code  \n\n      io.on(\'connection\', socket => {\n        console.log(\'A user has connected\');\n        ++currentUsers;\n        io.emit(\'user count\', currentUsers);\n    });\n\n\n\n    //end socket.io code\n  \n  \n});\n' to match /socket.on.*('|")disconnect('|")/gi

server.js

'use strict';

const express     = require('express');
const session     = require('express-session');
const bodyParser  = require('body-parser');
const fccTesting  = require('./freeCodeCamp/fcctesting.js');
const auth        = require('./app/auth.js');
const routes      = require('./app/routes.js');
const mongo       = require('mongodb').MongoClient;
const passport    = require('passport');
const cookieParser= require('cookie-parser')
const app         = express();
const http        = require('http').Server(app);
const sessionStore= new session.MemoryStore();
require('dotenv').config()
const cors        = require('cors');
const io = require('socket.io')(http);

app.use(cors());

fccTesting(app); //For FCC testing purposes

app.use('/public', express.static(process.cwd() + '/public'));
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', 'pug')
var currentUsers = 0;



app.use(session({
  secret: process.env.SESSION_SECRET,
  resave: true,
  saveUninitialized: true,
  key: 'express.sid',
  store: sessionStore,
}));


mongo.connect(process.env.DATABASE, (err, db) => {
    if(err) console.log('Database error: ' + err);
  
    auth(app, db);
    routes(app, db);
      
    http.listen(process.env.PORT || 3000);

  
    //start socket.io code  
      io.on('connection', socket => {
        console.log('A user has connected');
        ++currentUsers;
        io.emit('user count', currentUsers);
    });

  io.on('disconnect', () => {
   --currentUsers; });



    //end socket.io code
  
  
});

$( document ).ready(function() {
  
  /*global io*/
var socket = io();

   
  // Form submittion with new message in field with id 'm'
  $('form').submit(function(){
    var messageToSend = $('#m').val();
    //send message to server here?
    $('#m').val('');
    return false; // prevent form submit from refreshing page
  });

});


  socket.on('user count', function(data){
  console.log(data);
	});

   socket.on('disconnect', (user) => {
        io.emit('disconnect', user);
        console.log(socket.name + ' has left the chat.');
    });

Remove the disconnect event from the client js

You need to put the disconnect event inside the server.js connection event.

io.on('connection', (socket) => {
  console.log('A user has connected');
  ++currentUsers;
  io.emit('user count', currentUsers);
  socket.on('disconnect', () => {
    console.log('A user has disconnected');
    --currentUsers;
    io.emit('user count', currentUsers);
  });
});

The client side should only respond to user count as the client side disconnect event is for when the server disconnects or goes offline.

The server side has the disconnect event inside the connection event because the connection event supplies the socket obj for the current connection.

12 Likes