How can I pass an already connected socket from socket.io to the controller when making a post request from the application to the server, using Vue and a Node server with Socket.io?
I attempted declaring global.io = io, but the socket remains undefined. Executing io.socket.join(room_id); returns undefined.
server.js
var app = require('express');
var server = require('http').Server(app);
var io = require('socket.io')(server);
const port = 3002;
const cors = require('cors');
const bodyParser = require('body-parser');
const routes = require('./routes/routes');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true,}));
app.use(cors());
app.use('/api', routes);
global.io = io;
// Start the server
server.listen(port, (error) => {
if (error) return console.log(`Error: ${error}`);
console.log(`Server listening on port ${server.address().port}`);
});
// Sockets on
io.sockets.on('connection', (socket) => {
// User connected
console.log("A user connected");
......
});
controller.js
const pool = require('../data/config');
const validator = require('validator');
const auth = require('../models/jwtModel');
const errors = require('../data/errors');
module.exports = {
games: function(req, res){
...
},
create: function(req, res){
...
},
join : function(req, res){
// Got a number
// Other actions
......
// Does not work
// You need to attach the current socket to this room and send a message to this room
// How can a connected socket be passed from the server.js?
socket.join(room_id);
io.sockets.in(room_id).emit('room.change',{type: "room.start"});
res.status(200).send({code: 0, room_id: room_id});
},
leave : function(req, res){
...
},
}
routes.js
var express = require('express');
var router = express.Router();
var controller = require('../controllers/controller');
router.route('/controller').post(controller.join);
module.exports = router;