HTML file can't connect to socketio

Viewed 334

I have a fresh HTML file in my file system as shown:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Minimal working example</title>
</head>

<body>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script>
    <script>
        const socket = io("http://localhost:5000", {
            transports: ['websocket']
        });

        socket.on('connect', () => console.log("connect"));
    </script>
</body>

</html>

I also have a javascript socketio server that was run on localhost:

const express = require("express")
const SocketIO = require("socket.io")
const http = require("http")

const app = express()
const PORT = process.env.PORT || 5000

const server = http.createServer(app)
const io = SocketIO(server)

app.get("/", (_, res) => res.send("Home"))

io.on("connection", socket => {
    console.log("connection!")
})

server.listen(PORT, () => console.log(`Sever running on ${PORT}`))

Why does my server never log anything???

2 Answers

Serve the front end from the same backend

After a bit of a closer inspection, your not serving your HTML file from the same host/port. Chances are your index.html file is getting a CORS error when trying to connect because it is cross origin without approval.

I replaced this line:

app.get("/", (_, res) => res.send("Home"))

with this line. to serve the index.html file from the same folder (not recommended)

app.use(express.static('.'))

With both running on the same domain, the connection logged successfully.

After dwelling in the lands of JavaScript for a long time, I found a solution to this issue which might be helpful to anyone who sees this post.

The solution to this issue was to change the version of socket.io I was using. I am unsure of what version the server was using in the example above. I tried running the same scripts again, but this time using the most up to date and compatible server and client versions of socket.io (v4.x). The sockets managed to connect, no matter the protocol (file:/// or http://).

enter image description here

This is in the socket.io docs here. If you want your sockets to connect, make sure the client and server versions are compatible. Because of this, I'm assuming that it was version incompatibility that was the issue when I created this post.

I hope that this post helps someone :D

Related