''http://127.0.0.1:5500' has been blocked by CORS policy

this is index.html code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Secret</title>
    <script defer src="http://localhost:8000/socket.io/socket.io.js"></script>
    <script defer src="./client/client.js"></script>
    <link rel="stylesheet" href="./css/index.css">
</head>
<body>
    <div class="main">
        <div class="head">this is a chat app</div>
        <div class="container">
            <div class="message right">Lorem ipsum dolor sit qui.</div>
            <div class="message left">Lorem ipsum dolor sit, amet consectetur adipisicin</div>
        </div>
        <div class="send">
            <form action="#" id="send_msg">
                <input type="text" name="messageInput" placeholder="type message😐" id="text">
                <button class="btn" type="submit">send</button>
            </form>
        </div>
    </div>
</body>
</html>

This is client.js code

const socket=io('http://localhost:8000');

//get dom elements in a js variable;
const form=document.getElementById('send_msg');
const messageInput=document.getElementById("messageInput");
const messageBox=document.getElementsByClassName("container")

const audio=new Audio('ring.mp3')

const append=(message,position)=>{
    const msgElm=document.createElement('div');
    msgElm.innerHTML=message;
    msgElm.classList.add('message');
    msgElm.classList.add(position);
    messageBox.append(msgElm);
    if(position=='left'){
        audio.play()
    }
}

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

socket.emit('user-joined',name=>{
    append(`${name} joined the chat`,'left');
})

socket.emit('receive',name=>{
    append(`${data.name}:${data.message}`,'left');
})

socket.emit('left',name=>{
    append(`${name}: leave the chat`,'left');
})

form.addEventListener('submit',(e)=>{
    e.preventDefault();
    const msg=messageInput.value;
    append(`You: ${message}`,'right');
    socket.emit('send',message);
    messageBox.value="";
});

This nodeJS code

//Node server which will handle socket io connections
const express=require('express');
const app=express();
const io=require('socket.io')(8000);

const cors=require('cors');
app.use(cors({
    origin: "http://127.0.0.1:5500/index.html",
}))

const users={};

io.on('connection',socket=>{
    // if any new user joins,let other users connected to the server know
    socket.on('new-user-joined',name=>{
        console.log(name);
        users[socket.id]=name;
        socket.broadcast.emit('user-joined',name);
    });

    //if someone sends a message,broadcast it to other people
    socket.on('send',message=>{
        socket.broadcast.emit('receive',{message:message,name:users[socket.id]})
    });

    //if someone leaves the chat, let others know
    socket.on('disconnect',message=>{
        socket.broadcast.emit('left',users[socket.id]);
        delete users[socket.id];
    })
})

here the error

"Access to XMLHttpRequest at 'http://localhost:8000/socket.io/?EIO=4&transport=polling&t=Npx4qzO' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

localhost:8000/socket.io/?EIO=4&transport=polling&t=Npx4qzO:1 Failed to load resource: net::ERR_FAILED

GET http://localhost:8000/socket.io/?EIO=4&transport=polling&t=Npx4x79 net::ERR_FAILED"

imageenter image description here



Solution 1:[1]

Try:

app.use(cors({
    origin: "http://localhost",
}))

or to allow all, use this, but then change it. This is for validation\testing.

app.use(cors())

Solution 2:[2]

You can run socket.io with standalone.

const { Server } = require("socket.io");

const io = new Server({
    cors: {
        origin: "http://127.0.0.1:5500",
        methods: ["GET", "POST"]
    }
});

io.on("connection", (socket) => {
    // Socket codes...
});

io.listen(8000);

Solution 3:[3]

Try this This is more detailed and gives you more control over CORS configuration

// Add a new entry of link that you wish to allow

const allowedOrigins = [
  'capacitor://localhost',
  'ionic://localhost',
  'http://localhost'
];

// Reflect the origin if it's in the allowed list or not defined (cURL, Postman, etc.)

const corsOptions = {
  origin: (origin, callback) => {
    if (allowedOrigins.includes(origin) || !origin) {
      callback(null, true);
    } else {
      callback(new Error('Origin not allowed by CORS'));
    }
  },
};

Solution 4:[4]

//Node server which will handle socket io connections
const express=require('express');
const app=express();
const io=require('socket.io')(8000);

const cors=require('cors');
app.use(cors({
    origin: "http://127.0.0.1:5500/index.html",
}))

const users={};

io.on('connection',socket=>{
    // if any new user joins,let other users connected to the server know
    socket.on('new-user-joined',name=>{
        console.log(name);
        users[socket.id]=name;
        socket.broadcast.emit('user-joined',name);
    });

    //if someone sends a message,broadcast it to other people
    socket.on('send',message=>{
        socket.broadcast.emit('receive',{message:message,name:users[socket.id]})
    });

    //if someone leaves the chat, let others know
    socket.on('disconnect',message=>{
        socket.broadcast.emit('left',users[socket.id]);
        delete users[socket.id];
    })
})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Huthaifa Muayyad
Solution 2 tepeumut
Solution 3 Nishant S Vispute
Solution 4 I AM WHOM I AM I AM WHO I AM