Sunday, 12 August 2018

Using Socket.io in Specific Route After Authorization

I am trying to let a user to connect via socket.io when the user has requested the "/messages" route, not the '/' index route. This connection to socket.io can only happen after the user has signed in. However, I am having difficulty doing so.Here's the code. I am not sure if it's the correct implementation:App.js//Import modules var express = require("express"), app = express(), //Mount to Node.js and connect to socket.io var server = require('http').Server(app); var io = require('socket.io')(server); //Import routes var indexRoutes = require("./routes/index"); var messagesRoutes = require("./routes/messages"); //Connect to socket.io when user request '/messages' route app.use("/", indexRoutes); app.use("/messages", messagesRoutes); //Listening request server.listen(process.env.PORT); /routes/messages.js:var express = require("express"); var router = express.Router(); var checkSignIn = require("../checkSignIn"); var User = require("../models/user"); //Respond with messages page, only if the user has signed in. router.get("/messages", checkSignIn, function(req, res){ User.findById(req.user._id, function(currentUser){ res.render("messages"); //Connect to Socket.io for each user connection io.on('connection', function(socket){ console.log('a user connected'); }); }); }); module.exports = router; Another thing is each user should be able to message another specific user, not all of the connected users.I found that we can use io.to(\${socketId}`).emit('someone', 'messages')`, but I am not sure how to obtain the 'socketId' of the specific user. I am hoping to use the database 'object.id' of the user its 'socketId', since each user are associated with their own mongoDB object.id in the database.

Submitted August 12, 2018 at 07:51AM by VickNicks

No comments:

Post a Comment