Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

233
Vistas
io.on is not working while making connection using socket.io

I am facing a problem (very frustrated), while I am connecting the io.on function. I am following a youtube tutorial(https://www.youtube.com/watch?v=3QNBVG2yqKA), where a chat application is made using node js and socket io. The code in the tutorial and mine are matching exactly same(checked 100 times), but mine code is not working.

Server-side code

//Node server
const io=require('socket.io')(3000);

const users={};
io.on('connection', socket=>{
    console.log("hi");
    socket.on("new-user-joined",name=>{
        console.log("name",name);
        users[socket.id]=name;
        socket.broadcast.emit("user-joined",name);
    });
    socket.on("send",message=>{
        socket.broadcast.emit("receive",{message: message, name:users[socket.id]});
    });
});

CLIENT Side Code

const socket=io.connect("http://localhost:3000");
const form=document.getElementById("sendContainer");
const msg=document.getElementById("messageInp");
const msgContainer=document.querySelector(".container");

const append=(message,position)=>{
    const messageEle=document.createElement("div");
    messageEle.innerText=message;
    messageEle.classList.add("message");
    messageEle.classList.add(position);
    msgContainer.append(messageEle);
}

const name1=prompt("Enter your name to join");
socket.emit("new-user-joined", name1);

socket.on("user-joined", name=>{
    append(`${name} joined the chat`, "right");
})

server side code is not running beyond const users={} object, I tested using console log

and in the browser console this error is displaying

Error Image

Please Help me solving this.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You need to add the cors object while initiating the socket in which you should add origins, otherwise it blocks the request.

cors: {
    origins: [],
  },

You can check the socket docs here for handling cors :https://socket.io/docs/v4/handling-cors/

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda