Error message "Uncaught ReferenceError: io is not defined" is displayed by Socket.io

I've been working on integrating sockets into my app, but have run into an error https://i.stack.imgur.com/4lUF7.png

Interestingly, when I tested the socket functionality in a separate test app using the same code, everything worked perfectly. However, within my main app, something seems to be amiss. I suspect it may have to do with having multiple HTML pages and needing to specify the paths correctly, but all of my attempts at doing so have failed.

Below is the current code that functions without issues in the test app but throws an 'io is not defined' error:

In the HTML:

https://i.stack.imgur.com/Sw3OI.png

In Node.js:


import http from 'http';
import { Server } from "socket.io";
const server = http.createServer(app);
const io = new Server(server);

io.on('connection', (socket) => {
  console.log('a user connected');
  socket.on('/chatmessage', (stuff) => {
    var currentUser = stuff.currentUser;
    db.collection('Messaging').where('Users',  'array-contains', currentUser).onSnapshot((querySnap) => {
      console.log('REALTIME CALLED')
      const doc = querySnap.docChanges()[0].doc;
        const data = querySnap.docChanges()[0].doc.data();
      var theObj = {id: doc.id, User1: data.User1, User2: data.User2, Users: data.Users, Last: data.Last, Created: data.Created, User1Messages: data.User1Messages, User2Messages: data.User2Messages }
      socket.emit('/chatmessagechange', dataToSend);

    }).catch((err) => {
      console.log(err);
      var dataToSend = {Error:"yes"};
      socket.emit('chat message change', dataToSend);
    })  
  })
});

The 'a user connected' log never shows up due to a client-side error when running the page. If the issue indeed stems from dealing with multiple HTML files and configuring paths properly, how should this be addressed? Thanks.

Answer №1

Regrettably, there is no interface var server in socket.io. If you intend to utilize socket on the front end, it is necessary to use socket.io-client instead. Check out this for more information.

import http from "http";
const socketIO=require("socket.io"); // make sure to modify it like this
const server = http.createServer(app);
const io = socketIO(server); // make sure to update it like this

io.on("connection", (socket) => {
  console.log("a user connected");
  socket.on("/chatmessage", (stuff) => {
    var currentUser = stuff.currentUser;
    db.collection("Messaging")
      .where("Users", "array-contains", currentUser)
      .onSnapshot((querySnap) => {
        console.log("REALTIME CALLED");
        const doc = querySnap.docChanges()[0].doc;
        const data = querySnap.docChanges()[0].doc.data();
        var theObj = {
          id: doc.id,
          User1: data.User1,
          User2: data.User2,
          Users: data.Users,
          Last: data.Last,
          Created: data.Created,
          User1Messages: data.User1Messages,
          User2Messages: data.User2Messages,
        };
        socket.emit("/chatmessagechange", dataToSend);
      })
      .catch((err) => {
        console.log(err);
        var dataToSend = { Error: "yes" };
        socket.emit("chat message change", dataToSend);
      });
  });
});

Answer №2

For me, I implemented the socket script in the head tag of my HTML document

<head>
    <script src="/socket.io/socket.io.js"></script>
    <script>
          var socket = io()
    </script>
</head>

If you are using react on the frontend, you can use the npm module socket.io-client. Otherwise, you will need to manually add the above code snippet in the HTML header section.

For further information, please visit: https://socket.io/docs/v3/client-api/

Thank you

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

Do I have to divide the small functions in my Node.js controller into smaller ones?

When signing up users in my controller, do I need to break up the sign-up steps into individual asynchronous calls or is one big asynchronous call sufficient? Each step relies on the previous one: Validate user Create user Create group Add user to group ...

Can you provide guidance on securing a REST API using Google authentication?

I'm currently working on developing a REST API using NodeJS and Passport for a single-page JavaScript application. I am struggling to find the right approach to securing my REST API with Google OAuth. Can someone guide me on how to achieve this? Any ...

What is the purpose of the .default() method being added to the class constructor in transpiled Typescript code

In TypeScript, I have the following code snippet to create an instance of ConnectRoles Middleware in Express: let user = new ConnectRoles(config); The middleware initialization is expected to be a simple call to a constructor. However, after transpiling, ...

Dependencies for a React application that is isomorphic/universal

As I embark on developing my first significant React application, I envisioned using Express to dynamically serve it. This raised an interesting consideration: should dependencies (excluding devDependencies) be limited solely to Express and perhaps a dep ...

Attempting to redeclare a previously exported variable will result in an error stating: "Cannot

I'm currently facing an issue with a npm module located in a different directory that I've linked to another project using npm link. Despite successfully compiling the typescript, when I try to import the module and use its function, I encounter ...

Building a Personalized Docker Image for Node.js and Selenium-Webdriver: Step-by-Step Guide

Having trouble getting my automation project to run in Jenkins. Issues with Docker images downloaded from the Internet and Linux agent compatibility with my Windows environment. I manually downloaded Google Chrome/Chromedriver in the build, but still can& ...

Showing button based on a particular value

I am trying to dynamically display a button based on the value of the sendSMS property for the logged-in user. I have added this property in the viewer model, which is connected to the user's base model. However, I am encountering difficulties with us ...

Solution: "The Mongoose Model.find method consistently provides an empty result set."

Currently, I am utilizing mongoose in combination with next.js to interact with an existing collection. Despite the collection not being empty, the mongoose model.find() function consistently returns an empty array. Below is my model code: const mongoose ...

When updating packages locally, NPM may throw an error but it still permits updating packages globally

https://i.stack.imgur.com/k6pkY.png When attempting to update packages locally to their most recent version, npm displays an error. However, updating them globally is possible. What is the reason for this and how can the ERESOLVE error be resolved in ord ...

What is the best way to download npm packages for offline use?

I need to install gulp on my project, but my development machine does not have an internet connection. The issue is that on another machine where I do have internet access, I am unable to install any software like node or npm. Is there a way for me to do ...

Having trouble with importing SendInBlue into my NodeJS application?

Currently in the process of updating my Node app to utilize ES6 import modules over requiring files. Encountering difficulties while trying to integrate this change with SendInBlue for email functionality, resulting in the following error message: TypeEr ...

Steps for opening standalone angular2 and TypeScript project in visual studio: A guide to launching your project

What is the process for accessing an Angular2 and TypeScript project in Visual Studio without needing npm or Node.js? I require the ability to open the project on a computer that is not connected to a network. Many thanks ...

dividing Handlebars HTML content into different files or sections

I am looking to design a single route webpage, but I would like to divide the HTML code into multiple files. When rendering this particular route, my goal is for the rendered file to pull content from different template files and combine them into one coh ...

A powerful combination of Node.js, Angular, and Jade on the client side, complement

Can anyone offer advice or examples on how to structure an app like this effectively? Client (client.company.com) Node.js Angular Jade ExpressJS Server (private) (server.company.com) node.js "rest" api (express) The API is currently private ...

How can I limit the input of string values from a Node Express request query?

export type TodoRequest = { order?: 'asc' | 'desc' | undefined; } export const parseTodoRequest = (requestData: ParsedQs): TodoRequest => { return { order: requestData.order as 'asc' | 'desc' | u ...

Setting the default views directory in express - A guide

I am currently struggling with setting up my routes in express.js properly. Below is a snippet of my code: express.js configuration app.set('views', config.root + '/app/views') app.set('view engine', 'jade') rout ...

Nestjs: Step-by-step guide to removing a specific application from a Nestjs monorepo using nest/cli

Is there a method to delete a specific app within a nestjs monorepo using the nest/cli? I have searched through the documentation and developer forums but cannot seem to find a solution. ...

Node JS failing to fulfill promises before returning

Seeking some assistance here. I have a series of promise-returning functions structured with .then() that ultimately formats data for the client. However, it seems that the server is sending the 'ff' variable to the client before the formatting f ...

How to install express using Terminal on a Mac operating system

Need some help with this code. Running it on my Mac with npm installed as an Admin, but still getting errors. I've been searching for a solution online for hours. Matts-MacBook-Pro-3:Start Matt$ npm install express-generator -g npm WARN checkPermissi ...

"Combining the power of Cloud9 with MongoDB and Node.js for

While working on a new project in Cloud9 IDE, I encountered an error when trying to deploy it on CloudFoundry from Cloud9IDE. The application failed to start. It seems like CloudFoundry uses a different port for listening. To address this issue, you sho ...