0

I've tried everything and I can't afford to waste any more time please need help, I've been trying to run the code in this post:https://medium.com/@mogold/nodejs-socket-io-express-multiple-modules-13f9f7daed4c,I've been trying to run the code in this post, I liked it a lot because as I see it fits very well with big projects, the problem arises when I want to connect to it, throws the following errors at me:enter image description here console: enter image description here I already try setting up the headers of my application and I've tried codes that I read from similar problems but none ah worked, I leave you the condigo of my server.ts, socket.ts, job.ts and routes.ts, I hope you can help me please :c

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;

enter image description here

3
  • Doesn't seem like you have any endpoints to hit from front end defined. Can you share contents of indexAppointment and indexUser. Also /socket.io shouldn't be what the front end hits, can you pass a custom path to the socket connection to test. You will need to define that subpath in your code. socket.io/docs/client-api look at custom path. Commented Sep 13, 2020 at 3:48
  • I just updated it, practically indexes them I use to separate logic from user paths and appointments Commented Sep 13, 2020 at 3:56
  • de casualidad hablas español ? :c Commented Sep 13, 2020 at 4:03

1 Answer 1

1

By default front end socket.io will connect to path /socket.io at the url provided. In your case it is localhost:3000. It doesn't seem like you have any routes re-defining this endpoint which is good.

The issue appears to be how the server is being started. You want http to be the listener here rather than the express app. So do the following,

Remove this part

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

And add this instead

  app.set( "ipaddr", "127.0.0.1" ); --> May be omitted since you're using a different ip. This way it lets app use the ip that it finds. So try it without first and see if that works. If not, then change to your ip.
  app.set( "port", 3000 );

  server.listen(3000, () => {

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

Sign up to request clarification or add additional context in comments.

5 Comments

I got this mistake :c http.listen(3000, () => {console.log('server is running on port', server.address().port); }); ^ TypeError: http.listen is not a function
no longer throws me any mistakes but I'm not getting the message from the client side, Do you have any idea that I'm doing wrong :c?, I just uploaded a photo, html is the same
You need to call the server so that in your backend code calls function emitUpdate. Since that's what will send the message to the front end. Currently nothing it's starting the communication so nothing is happening
I already work, seriously a thousand thanks, you saved my life hahaj a last consultation, in production is "ipaddr", "127.0.0.1" left in production?
It all depends how you server is hosted/deployed. Some servers use localhost, others use a range of ips. So I can’t really answer that since idk how you’re deploying this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.