0

I am trying to emit 'Hello World' from server.js but when I try to send 'Hello World', then, I get an error in console. I tried many socket.io code but every time I face this same problem. I even uninstalled and re-installed node.js but then also the issue did not get fixed.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>MeChat</title>
  <script defer src="http://localhost:3000/socket.io/socket.io.js"></script>
  <script defer src="script.js"></script>
  <style>
    body {
      padding: 0;
      margin: 0;
      display: flex;
      justify-content: center;
    }

    #message-container {
      width: 80%;
      max-width: 1200px;
    }

    #message-container div {
      background-color: #CCC;
      padding: 5px;
    }

    #message-container div:nth-child(2n) {
      background-color: #FFF;
    }

    #send-container {
      position: fixed;
      padding-bottom: 30px;
      bottom: 0;
      background-color: white;
      max-width: 1200px;
      width: 80%;
      display: flex;
    }

    #message-input {
      flex-grow: 1;
    }
  </style>
</head>
<body>
  <div id="message-container"></div>
  <form id="send-container">
    <input type="text" id="message-input">
    <button type="submit" id="send-button">Send</button>
  </form>
</body>
</html>

package.json

{
  "name": "mechat",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "devStart": "nodemon server.js"
  },
  "author": "Somenath Choudhury",
  "license": "ISC",
  "dependencies": {
    "socket.io": "^3.0.1"
  },
  "devDependencies": {
    "nodemon": "^2.0.6"
  }
}

server.js

const io = require('socket.io')(3000)

io.on('connection', socket => {
    socket.emit('chat-message', 'Hello World')
})

script.js

const socket = io('http://localhost:3000')

socket.on('chat-message', data => {
    console.log(data)
})

The error I get whenever I try to print 'Hello World' in console:-

Access to XMLHttpRequest at 'http://localhost:3000/socket.io/?EIO=4&transport=polling&t=NNAe6YZ' 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:3000/socket.io/?EIO=4&transport=polling&t=NNAe6YZ:1 Failed to load resource: net::ERR_FAILED
index.html:1 Access to XMLHttpRequest at 'http://localhost:3000/socket.io/?EIO=4&transport=polling&t=NNAe6vf' 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:3000/socket.io/?EIO=4&transport=polling&t=NNAe6vf:1 Failed to load resource: net::ERR_FAILED

0 Answers0