I created a user login with nodejs and mongodb. I have a router. I stripped some of the code out below, but the main routes I am concerned with in this question are the /profile
and /logout
routes.
Basically I want to pass the req
or res
data to the socket when the route is made. Since the routes are on the server I am not sure how to emit the data. I mean typically you emit from client to server and the other way around, not server to server.
So maybe I am being blind or am not knowledgeable enough, but my question is how can I pass that data to my socket.
module.exports.initialize = function(app, passport) {
app.get('/profile', isLoggedIn, function(req, res) {
res.render('profile', { user : req.user });
//socket.emit('user loggedIn', { user : req.user })
});
app.get('/logout', function(req, res) {
req.logout();
res.redirect('/');
});
// route middleware to make sure a user is logged in
function isLoggedIn(req, res, next) {
if (req.isAuthenticated())
return next();
res.redirect('/');
}
};
Side Note: My socket code sits in my server.js so example.
var users = {};
io.sockets.on('connection', function (socket) {
// Listen to a new user then emit the user to all clients
socket.on('user loggedIn', function (data) {
socket.userName = data;
users[socket.userName] = socket;
io.sockets.emit('user name', Object.keys(users));
console.log(users);
});
});
Basically I want to just store all the logged in users inside an object and emit to the client all the logged in users and allow them to have a live chat.
It appears all I need to do is pass that data to my socket, so I am sure passing that data is simple, but I DONT KNOW HOW!
Thanks!