Skip to content

Instantly share code, notes, and snippets.

@camperbot
Forked from ShaunSHamilton/client.js
Last active April 29, 2022 02:07
Show Gist options
  • Save camperbot/d7af9864375207e254f73262976d2016 to your computer and use it in GitHub Desktop.
Save camperbot/d7af9864375207e254f73262976d2016 to your computer and use it in GitHub Desktop.
Advanced Node and Express - Send and Display Chat Messages
$(document).ready(function () {
/* Global io */
let socket = io();
socket.on('user', (data) => {
$('#num-users').text(data.currentUsers + ' users online');
let message = data.name + (data.connected ? ' has joined the chat.' : ' has left the chat.');
$('#messages').append($('<li>').html('<b>' + message + '</b>'));
});
socket.on('chat message', (data) => {
console.log('socket.on 1');
$('#messages').append($('<li>').text(`${data.name}: ${data.message}`));
});
// Form submittion with new message in field with id 'm'
$('form').submit(function () {
let messageToSend = $('#m').val();
// Send message to server here?
socket.emit('chat message', messageToSend);
$('#m').val('');
return false; // Prevent form submit from refreshing page
});
});
'use strict';
require('dotenv').config();
const express = require('express');
const myDB = require('./connection');
const fccTesting = require('./freeCodeCamp/fcctesting.js');
const session = require('express-session');
const passport = require('passport');
const routes = require('./routes');
const auth = require('./auth.js');
const app = express();
const http = require('http').createServer(app);
const io = require('socket.io')(http);
const passportSocketIo = require('passport.socketio');
const cookieParser = require('cookie-parser');
const MongoStore = require('connect-mongo')(session);
const URI = process.env.MONGO_URI;
const store = new MongoStore({ url: URI });
app.set('view engine', 'pug');
fccTesting(app); //For FCC testing purposes
app.use('/public', express.static(process.cwd() + '/public'));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(session({
secret: process.env.SESSION_SECRET,
resave: true,
saveUninitialized: true,
cookie: { secure: false },
key: 'express.sid',
store: store
}));
app.use(passport.initialize());
app.use(passport.session());
io.use(
passportSocketIo.authorize({
cookieParser: cookieParser,
key: 'express.sid',
secret: process.env.SESSION_SECRET,
store: store,
success: onAuthorizeSuccess,
fail: onAuthorizeFail
})
);
myDB(async (client) => {
const myDataBase = await client.db('database').collection('users');
routes(app, myDataBase);
auth(app, myDataBase);
let currentUsers = 0;
io.on('connection', (socket) => {
++currentUsers;
io.emit('user', {
name: socket.request.user.name,
currentUsers,
connected: true
});
socket.on('chat message', (message) => {
io.emit('chat message', { name: socket.request.user.name, message });
});
console.log('A user has connected');
socket.on('disconnect', () => {
console.log('A user has disconnected');
--currentUsers;
io.emit('user', {
name: socket.request.user.name,
currentUsers,
connected: false
});
});
});
}).catch((e) => {
app.route('/').get((req, res) => {
res.render('pug', { title: e, message: 'Unable to login' });
});
});
function onAuthorizeSuccess(data, accept) {
console.log('successful connection to socket.io');
accept(null, true);
}
function onAuthorizeFail(data, message, error, accept) {
if (error) throw new Error(message);
console.log('failed connection to socket.io:', message);
accept(null, false);
}
http.listen(process.env.PORT || 3000, () => {
console.log('Listening on port ' + process.env.PORT);
});
@muhammedctgr
Copy link

any help? cant pass this test....my homepage loads for 2secs and crashes. if this doesnt have something to do with const passportSocketIo = require('passport.socketio'); thats deprecated which fcc/i keep using then its probably where the app is listening from which is supposed to be http...i dont know how to solve this

@harmonify
Copy link

@6ix-Ville have you solved this?
I suppose it is fine to use the deprecated package for this small project. I used the same package version with fcc and passed the test just fine.

@muhammedctgr
Copy link

Yes I have passed the test...used that same package as well. Thanks.

@johnson-elugbadebo
Copy link

Hi all, I am not getting a chat messages to display. I am seeing "John Doe has joined the chat." in the client. But I can't see any chats.
My code is identical to the code above. Any thoughts?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment