Combining the powers of Socket.io, node.js, and smart routing

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;

Answer №1

Connecting to the initial socket.

Give this a try

import express from "express";
import http from "http";
import cors from "cors";

const app = express()
// Remember to include bodyParser and cors
const server = http.createServer(app)
const io = new Server(server, {
 cors: {
     origin: "*" // Allows connection between back and front end on localhost or host
  }
})

io.on("connection", (socket) => {
  socket.on("join_room", async (room) => {
   console.log(`User ${socket.id} joined room ${room}`);
   socket.join(room)

  })
})


function emitToIO({ key, data }) {
  io.emit(key, data);
  console.log("key", key);
  console.log("data", data);
}

export default emitToIO

Your post route

import emitToIO from "../app.js"
router.post("/", (req, res) => {
  const data = req.body
  emitToIO({key: "identify_key", data: data}) // You can pass an object as data
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Steps to include a data-xx attribute in the displayed <table> within a Vuetify 2 v-simple-table

I am facing an issue where I want to include an HTML data-xxxx attribute to the HTML <table> within a v-simple-table. However, when I add the data attribute to the <v-simple-table>, it ends up being placed in a surrounding div two levels above ...

Is it possible to verify the existence of several arrays of data in a MongoDB database using Node.js?

I'm trying to verify if certain data exists in a database. If the data does exist, I want to set the value of k to 1. global.k = 0 let roll = {roll0:"1616",roll1:"234"} for (let i = 0; i < inputcount; i++) { let obj1 = roll["roll" + i]; const ...

Utilize Ionic and Angular to display the local storage value within a text box

I am in the process of developing an application using the Ionic framework. I am able to upload files to the server and receive a response, which I then save the file name in localstorage. However, I am facing an issue where I need to display this value in ...

Unable to utilize external JavaScript files in Angular 8

I've been working on integrating an HTML template into my Angular project and for the most part, everything is going smoothly. However, I've encountered an issue where my JS plugins are not loading properly. I have double-checked the file paths i ...

Customize your Bootstrap navbar dropdown to showcase menu items in a horizontal layout

I have been developing a new project that requires a navbar to be positioned at the center of the page, at the top. The current HTML code I am using is as follows... <div class="navbar navbar-inverse navbar-fixed-top center"> <div class="con ...

Error: Uncaught Type Error - Attempted to access property 'then' of an undefined variable. This issue occurred when attempting to use a

I attempted to use the code below, considering that node operates asynchronously and in order to execute my code sequentially I added a then function. However, I encountered the error TypeError: Cannot read property 'then' of undefined. The code ...

Pick a selection from a different input

Consider the following two rows: <tr> <td class="contenu"><input type="text" name="numart" id="numart"/></td> <td class="contenu"><input type="text" name="descart" id="descart"/></td> <td class="contenu"& ...

Despite Nodejs's efforts, it was unable to successfully populate the user

I have been able to successfully reference and store other documents in my mongodb database as objectids for my application. However, I am facing an issue with the .populate method not working as expected. Below is the code snippet that I am using for po ...

What is the mechanism behind the clipping function in the three.js frustum?

Currently, I am exploring the frustum feature of three.js by making changes to the example provided in the Scene Graph section here. function main() { const canvas = document.querySelector('#c'); const renderer = new THREE.WebGLRenderer({c ...

Tips for sending hidden variables created dynamically with Jquery

I recently developed a dynamic table for my project. You can check out the DEMO here. The dynamic table is nested within a div called 'box' in a form. <div id="box"> </div> To save the dynamically generated data, I am using Jquery ...

In what way does the Node console showcase decimal numbers in floating point format?

While I understand the challenges of representing base 2 numbers in base 10 due to rounding issues in programming languages, my experience with the NodeJs console has left me puzzled. It is a known fact that base 2 numbers cannot perfectly represent 0.1 in ...

What could be the reason for jQuery not loading when vendored in the Sinatra framework?

I'm currently attempting to vendor jQuery in my Sinatra app following a tutorial, but I'm facing issues getting jQuery to work. Typically, I rely on Google's CDN to load jQuery and it always works fine. However, when trying to vendor it, I&a ...

Can we determine the completion of an AJAX call using an Object-Oriented Programming approach?

Apologies for the vague title. Finding the right words to describe this was a bit challenging. This is what I'm looking into. Let's assume: function myClass() { $.ajax({ type:'get', url:'some/path/', suc ...

Bidirectional Data Binding in AngularJS

In my angular application, there is a dropdown with various values. When a user selects a specific value from the dropdown, I want to display the complete array corresponding to that value. <!doctype html> <html lang="en"> <head> < ...

Implementation of Repetition Function

When working with the TypeScript example above, I encountered 2 errors. The first error was related to `i` in the second console.log due to the use of the 'let' keyword. The second error was regarding 'test' in the first line, stating i ...

Passing PHP data to a JavaScript file using JSON格式

I have a query regarding how to pass php variables and send their values to a js file using json. Here is what I currently have: <?php $data = array('artist' => $artistname, 'title' => $songname); echo json_encode($data); // ...

The canvas's document.getElementById function is unable to find any matching element,

Hello everyone, I am currently diving into the world of javascript and trying to expand my knowledge. However, I have encountered a problem that has me stumped, and I could really use some assistance. While exploring, I came across this page: http://www.w ...

Is there a way to achieve a similar effect to "object-fit: cover" for CylinderGeometry in three.js while utilizing THREE.VideoTexture()?

I'm really interested in creating something similar to this: https://i.sstatic.net/mWuDM.png Imagine the checkered background as a texture, and I want the jar to be a cylinder with that texture applied to it. My knowledge of three.js is limited, so ...

Let the Vuejs transition occur exclusively during the opening of a slide

Trying to implement a smooth transition when the toggle button is clicked. Successfully applied the transition effect on the slider, but struggling to animate the text inside the div.hello class upon sliding open. <transition name="slide"> <a ...

What is the best way to ensure that FileReader's onload event has finished before proceeding?

Currently, I am facing an issue with the synchronous execution of the onLoad method using FileReader. The problem arises when the onLoad method does not execute synchronously with the rest of the code. Below are two functions that exemplify this issue: ...