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

Issue

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.

Solution

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/

Answered By – Prasanth Perli

Answer Checked By – Katrina (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.