socket.io "Cross-Origin request Blocked" 错误

socket.io "Cross-Origin request Blocked" error

因此,我正在尝试按照 this 教程进行操作,但马上就无法正常工作。 首先,这些是我的文件:

root/frontend/index.html

<html>
  [...]some static page[...]

  <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.js"></script>
  <script src="index.js"></script>
</html>

root/frontend/index.js

const socket=io('http://localhost:3000');

socket.on('init', handleInit);

function handleInit(msg) {
   console.log(msg);
}

root/server/server.js

const io=require('socket.io')();

io.on('connection', client =>{
  client.emit('init', {data:'hello'});
});

io.listen(3000);

他接下来要做的是 运行在前端文件夹中安装“npx live-server”(我也这样做)。而且,服务器文件夹中的运行“yarn add socket.io”然后运行“npx nodemon server.js”应该可以工作。但是执行那些确切的步骤我得到了错误: “跨源请求被阻止:同源策略不允许在 http://localhost:3000/socket.io/?EIO=3&transport=polling&t=NsGvIgN 读取远程资源。(原因:CORS 请求未成功)”

"GET http://localhost:3000/socket.io/?EIO=3&transport=polling&t=NsGvO1Z"

所以,我有点明白了。

最后,我学习了另一个教程,它更简单,对初学者来说也更好。是this one。通俗易懂,切中要点,紧凑,工作没有问题。

但是,如果您遇到此 CORS 错误,那么修复它的方法在 another 视频中。基本上你必须安装 cors 包并在服务器 js 代码中添加一些定义。修复本身在 10 分钟内,但我建议从头开始观看。