The socket.io client in my JavaScript code is failing to receive the necessary event

Currently, I am in the process of configuring a socket.io chat feature with an expressjs backend and sveltejs frontend.
I have established a custom namespace named 'chat' where a new room is generated upon a 'join' request.
My approach closely aligns with the official documentation.

Below is my code snippet:
Server:

const app = express();
const server = app.listen(3002);
log.info("Express server has started on port 3002");
const io = require("socket.io")(server, { path: "/api/express/socket.io" });
const chat = io.of("/chat");
chat.on("connection", socket => {
  log.info("New User connected");
  socket.on("join", room => {
    log.info("New User joined room: " + room);
    socket.join(room);
  });
  socket.on("chat message", data => {
    log.info("'chat-message'-Event: ", data);
    chat.in(data.room).emit("chat message", {
      room: data.room,
      msg: data.msg,
      user: data.user
    });
  });
});

Client:

let chatSocket
onMount(async () => {
    chatSocket = io('https://my.domain.com/chat', {
      path: '/api/express/socket.io',
      transports: ['websocket'],
    })
    chatSocket.on('connection', function(socket) {
      socket.on('chat message', function(data) {
         alert(data.msg)
      })
    })
    chatSocket.emit('join', 'Chat-Room#' + id)
  })
  const Submit = async e => {
    chatSocket.emit('chat message', {
      room: 'Chat-Room#' + id,
      msg: statusText,
      user,
    })
  }

Upon checking the server console output, everything appears to be configured correctly. All events are being triggered as expected and logged to console. However, the clients are not receiving any 'chat message' events (even though they are sending them successfully).
Do you have any insights into what might be going wrong here?

Answer №1

chatSocket.on('connection', function(socket) {
      socket.on('chat message', function(data) {
         alert(data.msg)
      })
    })

The code you are using is for the 'connection' event, but in the latest version of socketIO, this event does not exist. This means that the function might not work as intended. Make sure to check the documentation for the correct event names.

To fix this issue, update the code to:

chatSocket.on('connect', function() {
      chatSocket.on('chat message', function(data) {
         alert(data.msg)
      })
    })

Refer to the socketIO documentation for more information: https://socket.io/docs/client-api/#Event-%E2%80%98connect%E2%80%99

Remember that the event names on the frontend and server sides may differ, so ensure you are referencing the correct documentation for each.

Answer №2

It seems that the issue occurred because of an error in the nginx reverse proxy setup. I made sure to include the 'upgrade' and 'connection' headers for both the server and client, which successfully fixed the problem.

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

I am currently exploring React Router, but I am struggling to grasp this particular behavior

My Express server serves the Create-React-App build. When I access http://localhost:8000/ while the server is listening, my page loads correctly. However, if I reload the page or navigate directly to it from the navigation bar, instead of seeing the UI, pl ...

What is the best way to showcase information from multiple JSON files simultaneously?

Creating dynamic JSON URLs based on browser cookie data. var cookie = $.cookie('faved_posts'); The cookie contains IDs like 123456, 111111, 000001, etc. Now we need to request the JSON file for each ID in the cookie. We have: $.each(cookie, ...

Saving a complicated schema in Node using Mongoose fails to save or update when encountering an error

Greetings, I am facing challenges while trying to save a complex schema in MongoDB. const itemsSchema =new Schema({ cat: {type: String, required: true}, catItems: [{ items:{type: String}, isActive: {type: Boolean, default: true} }] }) ...

Exploring the depths of object properties with Angular, JavaScript, and TypeScript: A recursive journey

Let's consider an object that looks like this: const person = { id: 1, name: 'Emily', age: 28, family: { mother: { id: 101, name: 'Diana', age: 55 }, fathe ...

In Node.js, the mongodb+srv URI does not support including a port number

Currently, I am working on a project in nodejs using express js. I have encountered the following error: MongoDB connection error: MongoParseError: MongoDB+srv URI cannot contain a port number. In my "MongoDB Atlas" dashboard, I have obtained my "connecti ...

What is the mechanism by which a Node.js server handles incoming requests?

Suppose I am working with this code snippet. I am using ExpressJS, although the server part doesn't seem much different from vanilla Node.js. var express=require('express'); var settings=JSON.parse(fs.readFileSync('settings.json' ...

Get the ability to overlay text onto an image by using jQuery for downloading

Currently, I am facing an issue with an online photo editor in my project. The problem is that I am unable to download the image after adding and editing text on it. The texts added are editable but the image cannot be downloaded after the changes. I nee ...

Exploring Angular14: A guide to efficiently looping through the controls of strictly typed FormGroups

Currently, I am working on upgrading my formGroups to be strictly typed in Angular v14. Within my FormGroup, there is a specific block of logic that iterates through all the controls and performs an action (this part is not crucial as I am facing issues be ...

Retrieve the item within the nested array that is contained within the outer object

I have a collection of objects, each containing nested arrays. My goal is to access the specific object inside one of those arrays. How can I achieve this? For instance, take a look at my function below where I currently log each array to the console. Wha ...

The correct reading of JavaScript in HTML is a common source of confusion

After creating a basic application using the code provided in a forum thread and testing it on the worker sandbox MTurk site, I noticed a peculiar issue. The application runs smoothly when following the code from the forum answer directly. However, when at ...

Comparing strings with if-else statement

I am having trouble comparing strings in this array. For some reason, the strings are never equal. var person = ["Sam", "John", "Mary", "Liz"]; var searchedName = prompt("Enter name"); var resultMessage = ""; for (index in person) { var currentName = ...

Explanation of the field definition is not clear in jwt.sign

How should the exp field of the payload be represented? jwt.sign({ _id: this._id, email: this.email, name: this.name, exp: //what is the correct way to set this value?, }, "MY_SECRET"); The documentation does not pro ...

Creating an interactive map on an image using HTML and drawing circles

I've been experimenting with drawing circles on images using the map property in HTML. I have an image set up, and when clicking on the image in JavaScript, I'm adding the area coordinates for the map property. However, I keep encountering a null ...

Conditionally changing the page view content through a knockout if statement

One challenge I am facing involves a dropdown list with two options. Each option, when selected, should change the display of content in the view. How can I connect my dropdown selection to show one content and hide the other? This is what I currently hav ...

What are some effective techniques for handling asynchronous operations while utilizing [displayWith] in an autocomplete

In my angular reactive form, I am struggling with an autocomplete functionality. I want to show the name (myObject.name) but use the ID (myObject.id) as the value. However, when the form is populated with existing values, there is a delay in retrieving th ...

Angular has developed a content script that automatically fills in user passwords on forms

I have developed a content script extension that automatically fills in user and password fields on webpages. It works perfectly fine on regular forms like the one below - <input name="userId" class="form-field" id="userId" placeholder="Username" autoc ...

Error encountered: 'applePaySession.completeMerchantValidation' is not a valid object reference when attempting to process a successful apple pay payment

So, I'm having an issue with the user's payment going through but encountering undefined value when checking compatibility. I've been trying to debug this problem in my code snippet below: setCanDisplayApplePay() { var client = n ...

I am looking to enhance my array of objects by implementing a filter. It is important that the filter does not allow for duplicate checkboxes with the

My website : On the left-hand side of my webpage, there is a set of checkboxes with some repeated names that I don't want. For example, "Rice" is repeated twice but I only want it to display once. When checking the Rice checkbox, it should show all c ...

React SVG not displaying on page

I am facing an issue with displaying an SVG in my React application. Below is the code snippet: <svg className="svg-arrow"> <use xlinkHref="#svg-arrow" /> </svg> //styling .user-quickview .svg-arrow { fill: #fff; position: ...

The method of utilizing React with Redux to display component properties

I am currently trying to include my common component in my main.js file Successfully implemented this However, when attempting to print my Redux data values in the common component, I created a method called handleClickForRedux to handle this task. Even af ...