The attempted JavaScript socket emissions from the server to the client for listening are currently experiencing difficulties and

I have encountered a peculiar issue with my code. It involves emitting from the server side and listening on the client side. The connection seems to persist indefinitely, even when the client refreshes or exits the page. However, the code on the client side does not execute and no errors are being displayed in the logs.

ServerSide Code:

io.on('connection', function(socket) {
        console.log("New socket connection");

        

        socket.on('joinApp', ({msg, password}) =>{

            let username;
            let rooms;

            
            model.findOne({username: msg}, function(err, found){
                if(!err){
                    var checka = false;
                    if(found){
                        if(found.password === password){
                            user = userLogged(socket.id, msg, found.rooms);
                            username = getUserName(socket.id).username;
                            rooms = getUserName(socket.id).rooms;
                            console.log(msg + " Has entered the chat");
                            console.log(socket.id);
                            checka = true;
                        }else{
                            console.log("Incorrect password");
                        }
                    
                    
                    }else{
                        console.log("User not found");

                    }
                    io.to(socket.id).sockets.emit("checker", checka);
                }
            });

        
        


            socket.on('myRooms', () =>{
                let user = getUserName(socket.id);
                let username = user.username;
                let rooms = user.rooms;

                if(user.rooms.length === 0){
                    console.log(username + " You have no rooms");
                    socket.emit("yourRooms", {username, rooms});
                }else{


                }

            });









        socket.on('disconnect', () => {
            console.log("Disconnected");


        });


        });

});

This is the code I am using in my Express.js file. In particular, this line has been causing issues:

io.to(socket.id).emit("yourRooms", {username, rooms});

The problem lies here - I emit the signal expecting the client to listen to it (Clientside code below):

let title = document.getElementById("title");
let rooms = document.getElementById("rooms");


    console.log(socket.id);

    socket.on("yourRooms", (username, rooms) => {


        if(rooms.length === 0){
            rooms.innerHTML = "You have no rooms";
        }

        title.innerHTML = user + "'s rooms";


    });

This section of the code correctly displays the socket.id of the client, indicating no issues.

console.log(socket.id);

I refrained from declaring another socket instance as that approach did not yield results.

In another part of my code, following this exact practice works fine. This exists in the file where I initialized my socket instance:

const socket = io();

I have spent hours troubleshooting but have not come across any errors in the logs. Additionally, the socket.id appears correct when logged in the problematic clientside script. I'm unsure of what mistake I might be making.

Answer №1

You are broadcasting an object in express

io.to(socket.id).emit("yourRooms", {username, rooms});

And you are listening for different parameters in client side

socket.on("yourRooms", (username, rooms) => {

Consider updating it to

socket.on("yourRooms", ({username, rooms}) => {

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

Navigate back to the previous route within the Vue router hierarchy

In my Vue application, I have a Settings page with child routes such as settings/user, settings/addUser, etc. I am looking to implement a back button that when pressed, takes the user back to the specific page they visited within the Settings section. Usin ...

Reposition the span element to the right of the div tag

I need help adjusting the positioning of the elements in this HTML code. How can I move the span element with the image to the right of the div tag? Here is the code snippet: <div style='width:600px;padding-top: 2px;padding-bottom: 1px'& ...

What's the best way to prevent extra spacing when typing in a materialUI TextField?

Instructions for the user: Please input your first name without any spaces between characters. I attempted to implement the following code, however, it did not achieve the desired outcome. <TextField required id="name" label="First Name" ...

Generating a JavaScript object from a string to optimize its compatibility with datatables

This inquiry pertains to the plugin available at: var hidecols = '{"sClass": "Hide", "aTargets": [0]},{"sClass": "asdf", "aTargets": [1]},{"sClass": "qwer", "aTargets": [2]}'; var hidecolsobj = eval('(' + hidecols + ')'); ...

Issue with unrecognized expression in JQuery when processing Ajax response

Recently, I implemented a JQuery Ajax Form on my website. $('#modal-body-sign-in').on('submit', '#sign-in', function(e) { e.preventDefault(); var data = $(this).serialize(); var url = $(this).attr(&apo ...

Reorganize a list based on another list without generating a new list

Among the elements in my HTML list, there are items with text, input fields, and tables. I also have a specific order list like [3,1,2,0]. Is it feasible to rearrange the items in the HTML list on the page based on this order list without generating a new ...

JavaScript - Modifying several object properties within an array of objects

I am attempting to update the values of multiple objects within an array of objects. // Using a for..of loop with variable i to access the second array and retrieve values const AntraegeListe = new Array(); for (let i = 0; i < MESRForm.MitarbeiterL ...

Tips for positioning HTML elements at the exact mouse location as it moves, without any delay?

Currently, I am in the process of developing a web-based drawing application that does not rely on using a canvas. My decision to avoid using a canvas is because I plan to incorporate CSS Keyframes into the HTML elements upon placement. This approach allow ...

Running multiple npm scripts on both Unix and Windows systems can be achieved by using the "npm

Is there a way for me to execute multiple npm scripts synchronously, one after another? Below are the npm scripts I have in my project, which includes both bower and npm packages: { "scripts": { "installnpm": "npm i", "installbower": "bower i", ...

Next.js Error: Unable to access the 'collection' property, as it is undefined

I have recently started using next.js and I am interested in creating a Facebook clone by following YouTube tutorials. However, I keep encountering the error message "Cannot read properties of undefined (reading 'collection')". To troubleshoot, I ...

Guide on transferring files between Node.js/Express servers from receiving files at Server A to sending files to Server B

Currently, I'm tackling node.js express servers and I've hit a roadblock! Despite my efforts to scour the documentation and other resources, I can't seem to find the right solution. Here's what I need to accomplish: Receive 2-3 PDF ...

JavaScript callbacks are not executed synchronously

My Objective : I am attempting to initiate a payment order in the payment gateway server and then send back the order details to the client using Firebase cloud functions. This process involves utilizing firebase cloud functions. The Order() function ha ...

I can't figure out why I keep receiving the InvalidArgumentError for H.Map with Argument #0 [object Object]

I recently refactored the code taken from the Maps API for JavaScript "Working with React" section. As a beginner in React and currently learning it in school, I have to utilize functional components. The material provided guidance on class component syn ...

Maintain the link's functionality even after it's been clicked by utilizing the same

I have a fixed navbar with same-page anchors and I want to keep the link active after it has been clicked and taken to that section of the page. While this is simple for links to another page, I'm struggling to figure out how to do it here. Here&apos ...

Iterate using jQuery through all child div elements

<div id="SelectedSection" class="selected"> <div class="sec_ch" name="7"> <div class="sec_ch" name="8"> <div class="sec_ch" name="9"> <div class="sec_ch" name="11"> <div class="clear"> </div> </di ...

What is the best way to organize class usage within other classes to prevent circular dependencies?

The engine class presented below utilizes two renderer classes that extend a base renderer class: import {RendererOne} from "./renderer-one"; import {RendererTwo} from "./renderer-two"; export class Engine { coordinates: number; randomProperty: ...

What is causing this issue? Error: [$compile:nonassign] The expression 'undefined' cannot be assigned! AngularJS 1.5

I'm currently working on developing a component to post "Tweets" on my personal website. However, I am facing an issue where I cannot input any text into the textarea. Below is an image showcasing the error: Please review my code in the file "editor ...

What is the best way to combine relative paths or create distinct identifiers for SVG files located within multiple layers of folders

I have a collection of icons exported from "Figma" organized in folders, and I'm using grunt-svgstore to create a sprite sheet. However, the result contains duplicated IDs even after trying 'allowDuplicateItems: false' and 'setUniqueIds ...

Utilizing jQuery to Calculate Tab Scores

Last week, my teacher and I collaborated on a fun game called rEAndom game (). The game is created using javascript, jQuery, and HTML5. One interesting feature of the game is that when you press the TAB key, a div displaying the score appears. You can chec ...

How to properly declare an explicit injector when using the resolve parameter in $routeProvider?

$routeProvider resolve feature in AngularJS allows for injecting additional dependencies to the controller function. How can we combine this with explicit dependency injection declaration? Example: angular.module('myModule', []) .config(func ...