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

An issue arose when attempting to access a Mashape web service with JavaScript

I am attempting to make use of a Mashape API with the help of AJAX and JavaScript. Within my HTML, I have a text area along with a button: <div> <textarea id="message" placeholder="Message"> </textarea> <br><br> ...

Utilizing Twitter Bootstrap to populate form fields from a dropdown selection

I am currently using twitter bootstrap for my front end web development project. I have successfully implemented a text field with a dropdown menu right next to it: <div class="input-group"> <input type="text" class="form-control" name="ope ...

Please execute the npm install command to install the readline-sync package in order to fix the error in node:internal/modules/c

Having trouble installing npm readline as it keeps showing errors, even after trying different solutions. Tried deleting folders and uninstalling nodejs but the issue persists. Need help fixing this problem. ...

AngularJS Filter without creating a new object

Within my code, I am dealing with an array of objects that contain sub-objects. This particular array is utilized in an ng-repeat to display data in a table format. To illustrate, consider the following example: device { "name": "computer" ...

Fade the current Div out and fade in the following Div while also animating its child element

Looking to achieve a fade in and out effect for 3 divs, with the child element animating its way up from the bottom right once the divs have faded in. I've been working on it but haven't made much progress, does anyone have any ideas? Check out ...

steps for adding text to the header with selenium webdriver

I came across the following code snippet: <body> <table> <tr> <td style= "width:30%;"> <img class = "new" src="images/new-icon.png"> <td> <h1>Hello there!</h1> ...

Align the date input field to the center for better visual appeal

I am facing a challenge in centering the date in an input, not the entire input element inside a div. When I attempt to center it, the date gets positioned within a portion of the input due to a resizable right-hand side panel for selecting a date from a c ...

Trouble Arising in Showing the "X" Symbol upon Initial Click in Tic-Tac-Toe Match

Description: I'm currently developing a tic-tac-toe game, and I've run into an interesting issue. When I click on any box for the first time, the "X" symbol doesn't show up. However, it works fine after the initial click. Problem Details: ...

The Bootstrap switch feature may encounter issues when trying to operate on dynamically generated checkbox inputs

My website is equipped with a mix of essential scripts: jQuery, Bootstrap, Modernizer, and JSON2HTML. I am trying to implement the following code snippet: <script> $('#my01Switch').bootstrapSwitch({ onText: 'ON', ...

Transform the javascript ES6 class into a functional programming approach

I am interested in converting my reactjs class to a functional programming approach rather than using OOP. Can anyone provide guidance on how to achieve this? Please refer to my code snippet below. import * as h from './hydraulic'; const vertic ...

I am facing a recurring issue where I am unable to add new libraries to my node_modules directory due to encountering the same error every time I attempt to

An error occurred after running npm audit --force, causing a dependency issue in my Node_modules 0 verbose cli C:\Program Files\nodejs\node.exe C:\Users\Jenis\AppData\Roaming\npm\node_modules\npm\bin& ...

ElementUI Cascader not rendering properly

Utilizing elementUI's cascading selector to present data, I have crafted this code in accordance with the official documentation. <el-cascader v-model="address" :options="addressOptions" :props="{expandTrigger: 'hover'}" ...

Angular implementation of a dynamic vertical full page slider similar to the one seen on www.tumblr

I'm determined to add a full-page slider to the homepage of my Angular 1.x app After testing multiple libraries, I haven't had much luck. The instructions seem incomplete and there are some bugs present. These are the libraries I've experi ...

Issue with Material UI React JS Select component: Unable to deselect multiple values when more than one item is selected

Implementing a multiselect dropdown in material ui with specific conditions: The dropdown will contain [0 Apples, 1 Oranges, 2 Grapes]. By default, 0 Apples should be selected. None of the options can be unselected. If 0 Apples is selected and the user se ...

Node JS Client.query not returning expected results

Currently, I am developing a Web Application that interacts with my PostgreSQL database. However, when I navigate to the main page, it should display the first element from the 'actor' table, but unfortunately, nothing is being retrieved. Below i ...

If values are not provided during an update, they will be automatically set as null in the database

I am looking to update certain keys and values in my database. Currently, I have populated fields such as firstname, lastname, and now I wish to add profile pictures, contact numbers, etc. However, when I use the update method, the fields that are already ...

The timer will automatically refresh when the page is refreshed

Currently, I am encountering an issue while working on a quiz application in PHP. The problem arises when users start the test and the timer is running correctly. However, when users move to the second question, the timer resets again. Below is the code sn ...

Ways to confirm non-null values and bypass the row if it is

I have been attempting to compare 2 dates in order to appropriately display data in a table. I have tried the following approach: ${this.dateToCompare.getTime()} > ${row.CreateDate.getTime()} However, there is an issue where CreateDate has a null value ...

Obtaining the translated text from the script in Vue JS using Vue Translate

My code currently looks something like this: <template> <div> {{ text }} </div> </template> <script> export default { data: () => ({ text: 'Hello world' }) } </script> I am tryin ...

Authenticate the user by comparing the entered username and password with the database records. If they match, proceed to redirect the user to their profile page. Otherwise, log

Attempting to complete this assignment which involves a user entering their username and password. If the information matches what is stored in the database, the user should be redirected to their profile page where a personalized greeting message is displ ...