如何在前端代码中保留 socket.io 客户端

How to keep socket.io client in frontend code

我正在学习 webdev,想尝试使用 Express 和 socket.io

制作一款多人游戏

我可以制作一个带有 socket.io 的服务器来监听。那部分工作正常。

然而,当我尝试连接客户端时,这仅在我让包含以下内容的 HTML 文件由服务器 served 时才有效,如下所示:

服务器代码:

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}`)
})

这个 index.html 底部有以下内容:

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

但是我想将所有前端代码与服务器分开。我为前端和后端创建了一个单独的存储库。我希望前端包含所有 UI 逻辑并仅使用数据调用 (AJAX) 从服务器获取 Json 数据。所以我只想把这个 index.html 文件放在我的前端代码中。

但是,如果我这样做,连接将无法正常工作。

我可以正常启动服务器。 我从 WebStorm 打开 index.html,它也为此创建了一个服务器,我配置为也监听端口 3000

但它找不到 /socket.io/socket.io.js,我在控制台中收到以下错误。 如果 WebStorm 在不同的端口上运行,它也不起作用。

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).

我如何才能将此 html 仅保留在我的客户端存储库中并仍然使用 socket.io,或者这是不可能的?

您不能让多个服务器侦听同一个端口。 运行 不同端口上的服务器以及:

  • 有一个反向代理转发请求到您的Socket.io服务器(需要special handling)和您的前端服务器
  • 在脚本 src 和 configure CORS 中放置绝对 URL。