如何使用 socket.io 库 link 一个 server.js 文件和一个 client.js 文件?

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

我正在按照 socket.io 教程构建一个简单的聊天应用程序。我已经在

的目录中安装了 socket.io

npm install socket.io

但没有任何效果,我收到错误消息

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.

这在我检查 index.html 文件时显示在浏览器上。 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>

Cross-Origin Request Blocked

来自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

嗯。是的。端口 3000 上的服务器 运行 设置为 socket.io 和 socket.io 提供服务。当客户请求 / 时,您没有告诉它确实提供了一些东西,所以它给您一个 Not Found 错误。