Search code examples
javascriptnode.jsserversocket.iochat

How to link a server.js file with a client.js file using socket.io library?


I'm following a socket.io tutorial to build a simple chat app. I've installed socket.io in the directory with

npm install socket.io

but nothing is working and I get the error message

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:3000/socket.io/?EIO=4&transport=polling&t=NuNNF0D. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 200.

This shows on the browser when I inspect the index.html file. Another error message shows up on localhost:300

GEThttp://localhost:3000/ [HTTP/1.1 404 Not Found 7ms]

The character encoding of the plain text document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the file needs to be declared in the transfer protocol or file needs to use a byte order mark as an encoding signature.

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

io.on('connection', socket => {
    console.log('new user');
    socket.emit('chat-message', 'hello');
})

//script.js
const socket = io('http://localhost:3000');

socket.on('chat-message', data => {
    console.log(data);
})
    <script defer src='http://localhost:3000/socket.io/socket.io.js'></script>
    <script defer src='script.js'></script>


Solution

  • Cross-Origin Request Blocked

    From the documentation:

    Since Socket.IO v3, you need to explicitly enable Cross-Origin Resource Sharing (CORS).

    const io = require("socket.io")(httpServer, {
        cors: {    
            origin: "https://example.com",    
            methods: ["GET", "POST"] 
         }
    });
    

    Another error message shows up on localhost:3000

    Well. Yes. The server running on port 3000 is set up to serve up socket.io and only socket.io. You've done nothing to tell it do serve up something when the client asks for / so it gives you a Not Found error.