Experiencing difficulties establishing a connection with my NodeJs server socket and TypeScript

I've been struggling to run the code from this post and I really need some help. The code can be found at: https://medium.com/@mogold/nodejs-socket-io-express-multiple-modules-13f9f7daed4c. I liked the code as it seems suitable for large projects, but I'm encountering errors when trying to connect to it. The errors are shown here:https://i.stack.imgur.com/UuKEp.png console: https://i.stack.imgur.com/l1GVv.png. I have tried setting up the headers of my application and also attempted various solutions I found online, but nothing has worked so far. Below, you will find the code snippets for server.ts, socket.ts, job.ts, and routes.ts. Any assistance would be greatly appreciated.

server.ts

 import  express  from "express";
    
    const http = require("http");
    import { router } from './routes/routes';
    import bodyParser from "body-parser";
    import morgan from "morgan";
    import { PORT } from "./core/utils/config";
    import errorMiddleware from './core/middleware/error.middleware';
    import socket from "./socket";
    
    const app = express();
    const server = http.createServer(app);
    
    
    app.use(bodyParser.json());
    app.use(router);
    app.use(morgan("dev"));
    app.use(errorMiddleware);
    app.listen(3000, () => console.log("[SERVER] list is running in port http://localhost:" + PORT));
    
    socket.connect(server);

socket.ts

let connection: any = null;

export class Socket {
  socket: any;

  constructor() {
    this.socket = null;
  }


  connect(server: any) {
    const io = require("socket.io").listen(server);
    io.on("connection", (socket: any) => {
      this.socket = socket;
    });
  }
  emit(event: any, data: any) {
    this.socket.emit(event, data);
  }

  static init(server: any) {
    if (!connection) {
      connection = new Socket();
      connection.connect(server);
    }
  }
  static getConnection() {
    if (connection) {
      return connection;
    }
  }
}


export default {
  connect: Socket.init,
  connection: Socket.getConnection
}

job.ts

import socket from "../../../socket";
export class JobSockets {

  emitUpdate() {
    const connection = socket.connection();

    if (connection) {

      connection.emit("jobs", {
        hola: "hola desde mi backend"
      });

    }
  }
}

routes.ts

    import express from "express";
    import indexAppointment from "../features/Appointment/routes/index";
    import indexUser from "../features/User/routes/index";
    import cors from "cors";
    
    const router = express.Router();
    const options: cors.CorsOptions = {
        allowedHeaders: [
            'Origin',
            'X-Requested-With',
            'Content-Type',
            'Accept',
            'X-Access-Token',
        ],
        credentials: true,
        methods: 'GET,HEAD,OPTIONS,PUT,PATCH,POST,DELETE',
        origin: "*",
        preflightContinue: false,
    };
    
    router.use(cors(options));
    router.options('*', cors(options));
    router.use(indexAppointment);
    router.use(indexUser);
    
    
    export {
        router
    };

client index.html

<html>

<head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.js"></script>
</head>

<body>
    <p>Check the console to see the messages coming through</p>
    <script>
        let socket;
        window.onload = () => {
            socket = io.connect("http://192.168.1.7:3000");
            socket.on("jobs", (msg) => {
                console.log(msg)
            })
        };
    </script>
</body>

</html>

import indexAppointment from "../features/Appointment/routes/index";

import expres from "express"
import getAppointment from "./getAppointment/getAppointment";
import createAppoinment from "./createAppointment/create_appointment";
import updateAppoinment from "./updateAppointment/update_appointment";
import deleteAppoinment from "./deleteAppointment/delete_appointment";

const router = expres.Router();

router.use("/appointment", getAppointment);
router.use("/appointment", createAppoinment);
router.use("/appointment", updateAppoinment);
router.use("/appointment", deleteAppoinment);


export default router;

import indexUser from "../features/User/routes/index";

import expres from "express"
import createUser from "./createUser/create_user";
import deleteUser from "./deleteUser/delete_user";
import updateUser from "./updateUser/update_user";
import getUsers from "./getUser/get_user";
import createUserInfoAppointment from "./createUserInfoAppointment/create_user_info_appointment";
import getUserInfoAppointments from "./getuserinfoappointment/get_user_info_appointment";

const router = expres.Router();

router.use("/user", createUser);
router.use("/user", deleteUser);
router.use("/user", updateUser);
router.use("/user", getUsers);
//managment use case
router.use("/user", createUserInfoAppointment);
router.use("/user", getUserInfoAppointments);


export default router;

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

Answer №1

When using front end socket.io, it will automatically connect to the path /socket.io at the provided URL. In this case, you are using localhost:3000. It seems that there are no routes re-defining this endpoint, which is a good thing.

The issue lies in how the server is being started. It is important to have http as the listener instead of the express app. Follow these steps:

Remove the following section:

  app.listen(3000, ()=> console.log("[SERVER] list is running on port http://localhost:"+PORT));

Replace it with this:

  app.set( "ipaddr", "127.0.0.1" ); --> You may omit this if you are using a different IP address. This allows the app to use the IP it finds. Try without it first and see if it works. If not, then change it to your specific IP.
  app.set( "port", 3000 );

  server.listen(3000, () => {

console.log('server is running on port', server.address().port); });

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

Neither of the elements within the ngIf statement is visible despite the fact that one of them should evaluate to true

I'm currently grappling with using ngIf to conceal a component's details until the necessary variable is set. During this waiting period, it should display a loading message. Despite my efforts to find a solution through online searches, I'v ...

npm publish is encountering an issue with the error message "Received undefined: The 'path' argument must be of type string."

I recently encountered an issue with my project that is published on a private npm repository. When using node v14.16.0 (npm v6.14.11), the command npm publish worked perfectly and my package was successfully published to the private repository. However, ...

Issue arises with server and browser construction while dealing with SSR

Encountering an issue with SSR: Error : Argument --output-hashing could not be parsed using value "false". Valid values are: "none", "all", "media", "bundles". Attempted to update the packages, but no changes occurred. { "name": "pictureline", "versi ...

Exploring the variations between getRequestHandler and render functions in Custom Next.js applicationsIn a

Greetings, I found it quite unexpected that there is a lack of information available on the functionalities of the getRequestHandler and render functions within the next package. As I am in the process of setting up a custom server, I am curious about wh ...

Saving child schemas of a MongoDB database using Mongoose

Here is the order object that I am currently working with - { shipper: { firstName: 'Test ShipName', address1: '10 Florida Ave', phone1: '800-123-4567' }, consignee: { firstName: 'AAA Man ...

Ways to prevent Jade (Node.js) from automatically closing the <body> tag

Attempting to deliver multiple data chunks to a client, each of which is processed by the Jade templating engine within the Express Node.js framework. Various views like header, viewA, viewB, viewC, etc., are at my disposal. For every request, I must ren ...

Why am I seeing back-end console errors that are related to my front-end?

Recently, I encountered an error message that prevents me from using 'import' in my front end code when trying to execute 'node index'. This issue never occurred before, and it only arose when I returned to this project. In my backend ...

NextJS middleware API receives an uploaded image file form, but the request is undefined

Currently, I'm utilizing NextJS to handle form data processing and database uploads, with a pit stop at the NextJS API middleware for image editing. pages/uploadImage.tsx This is the client-side code handler. ... async function handleImageUpload(imag ...

Create a debounce click directive for buttons in a TypeScript file

I'm facing an issue with implementing debounce click on a dynamically added button using TypeScript. I need help with the correct syntax to make it work. private _initActionsFooter(): void { this.actionsFooterService.add([ { ...

The VueJS component from a third-party source is not located in the node_modules directory

Utilizing vue-cli version 3 for a fresh vuejs project (I've been dedicating ample time to learning vuejs, but this marks my initial attempt at integrating a third-party component). I'm aiming to incorporate a visually appealing grid component. Th ...

Creating intricate mazes using canvas drawing techniques

I recently developed a maze generator as a personal project utilizing a graph. While the generation logic works perfectly, I am facing challenges when it comes to rendering the maze. In my approach, each cell is represented by an array of 4 edges where the ...

Express unable to render page using post request in NodeJS

I am currently utilizing Express v.2.4.6 (Node.js - v.0.6.2) and facing an issue with rendering or redirecting to a new page upon POST being called instead of GET. While I have successfully been able to render/redirect when GET is called, I am encountering ...

Sending data chunks through a pipe directly to a client's terminal as a Response

I'm currently working on implementing Node.js piping in my backend. The structure of my application involves a simple route that calls a function and passes a file path for an executable type file. This file is then executed using childProcess.spawn, ...

Create distinct Firebase Cloud Functions while harnessing the power of Express.js

There are numerous instances of utilizing Express for Firebase Cloud Functions. In all the examples I have come across, the code reveals the Express app as a singular Cloud Function: exports.app = functions.https.onRequest(app); For one's Firebase ...

Testing event emitters in node.js: a step-by-step guide

Imagine the scenario where I need to create a basic task. However, I also need to develop a test that validates the following criteria: The task should emit an object. The emitted object must have a property named "name". I am utilizing mocha and chai e ...

Is it possible to determine the remaining time in a Redis session using Node.js?

When setting up a redis-based session in Node.js using express.js, I have the following configuration: // Redis session const sessionStore = new RedisStore({ client: getRedisClient(), prefix: 'bl:', ttl: parseInt(config.sessionTTL, 10 ...

What could be the reason for the defaultCommandTimeout not functioning as expected in my script

Is there a way to wait for only one particular element in Cypress without having to add wait commands everywhere in the test framework? I've come across the solution of adding defaultCommandTimeout in the cypress.json file, but I don't want it t ...

Delete row from dx-pivot-grid

In my current project, I am utilizing Angular and Typescript along with the DevExtreme library. I have encountered a challenge while trying to remove specific rows from the PivotGrid in DevExtreme. According to the documentation and forum discussions I fo ...

Can an express middleware be implemented for a particular HTTP request method?

I am looking to incorporate an Express middleware that will be activated whenever a POST request is made, regardless of the route URL. I believe the following code snippet should achieve this: app.use(function (req, res, next) { if (req.method === &ap ...

Testing the controllers in Express is crucial for ensuring the functionality

When it comes to unit testing with Express, I've been facing some challenges due to the lack of documentation and information available online. I have discovered that I can test my routes using a library called supertest (https://github.com/visionmed ...