Skip to content
Advertisement

Unable to connect to socket – Vanilla JS to node.js

I am trying to work with socket.io, however I am unable to establish a connection between my client (Vanilla HTML/JS) and my server (node.js).

Server code:

const express = require('express');
var cors = require('cors');
const app = express();

app.use(cors())
app.use(express.json());
app.use(express.urlencoded());

var server = app.listen(3001, () => console.log('Listening on port 3001!'));
const io = require('socket.io')(server)

io.on('connection', (socket) => {
    console.log("A user connected");
    socket.on('disconnect', () => {
        console.log("user disconnected")
    })
})

I also have several endpoints and functions that are exposed in the same file, though they didn’t seem relevant (as far as I know), so I didn’t include them here, but can if needed.

HTML:

<head>
    <script src="https://cdn.jsdelivr.net/npm/socket.io-client@2/dist/socket.io.js"></script>
    <script src="../scripts/index.js"></script>
</head>

index.js:

window.onload = () => {
    var socket = io("http://localhost:3001")
    socket.on('connect', () => {
        console.log("Connected")
        console.log(socket.connected)
    })
    socket.on('test', () => {
        console.log("In test socket on")
    })
}

I don’t seem to be getting any errors thrown in the console or anything, and am not sure where the issue is coming from.

Advertisement

Answer

So as it turns out, the configuration I had for both the client and the server were ok, however it seems as though the issue was with the version of socket.io that I was using. The version I was using was 3.0.3, however when rolling it back to 1.7.4, the setup had worked and I was able to successfully connect to the socket. This isn’t an ideal situation by any means, I believe with version 3, the configuration has to be modified. As a quick, temporary fix, this may help, though of course this is by no means an ideal, production-level solution.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement