Home > Software design >  How to keep socket.io client in frontend code
How to keep socket.io client in frontend code

Time:02-16

I am just learning webdev and want to try to make a multiplayer game using Express and socket.io

I can make a server with socket.io in it which listens. That part works fine.

However when I try to connect a client, this only works if I let the HTML file with the following in it be served by the server like follows:

Server code:

const express = require('express')
const app = express()
const http = require('http')
const server = http.createServer(app)
const { Server } = require('socket.io')
const io = new Server(server)

const port = 3000

io.on('connection', (sock) => {
    console.log('client connected')
})

// This seems to be necessary, but I don't want it to be!!!
app.get('/', (req, res) => {
    res.sendFile(__dirname   '/index.html')
})

server.listen(port, () => {
    console.log(`Server listening on port ${port}`)
})

This index.html has the following at the bottom:

<script src="/socket.io/socket.io.js"></script>
<script>const socket = io()</script>

However I want to keep all my frontend code seperate from the server. I made a seperate repository for the frontend and backend. I want the frontend to contain all the UI logic and use only data calls (AJAX) to get Json data from the server. So I want to put this index.html file in my frontend code only.

Yet if I do this the connection doesn't work.

I can start the server fine. I open index.html from WebStorm which also creates a server for this which I configured to also listen to port 3000

Yet it cannot find /socket.io/socket.io.js and I get the following error in the console. It also doesn't work if WebStorm runs on a different port.

The resource from “http://localhost:3000/socket.io/socket.io.js” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff).

How can I keep this html in my client repo only and still work with socket.io, or is this not possible?

CodePudding user response:

You can't have multiple servers listening on the same port. Run the servers on different ports and either:

  • Have a reverse proxy forwarding requests to your Socket.io server (which needs special handling) and your front end server or
  • Put an absolute URL in the script src and configure CORS.
  • Related