简体   繁体   English

socket.io“跨域请求被阻止”错误

[英]socket.io "Cross-Origin request Blocked" error

So, I'm trying to follow along this tutorial and right off the bat I can't get it to work.所以,我正在尝试按照教程进行操作,但我无法立即使用它。 First off, these are my files:首先,这些是我的文件:

root/frontend/index.html根/前端/索引.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根/前端/index.js

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

socket.on('init', handleInit);

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

root/server/server.js根/服务器/server.js

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

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

io.listen(3000);

What he does next is running "npx live-server" in the frontend folder (which I also do).他接下来要做的是在前端文件夹中运行“npx live-server”(我也这样做)。 And also, run "yarn add socket.io" in the server folder and then run "npx nodemon server.js" and it's supposed to work.此外,在服务器文件夹中运行“yarn add socket.io”,然后运行“npx nodemon server.js”,它应该可以工作。 But doing those exact steps I get the errors: "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:3000/socket.io/?EIO=3&transport=polling&t=NsGvIgN. (Reason: CORS request did not succeed)"但是执行这些确切的步骤我得到了错误:“跨域请求被阻止:同源策略不允许读取 http://localhost:3000/socket.io/?EIO=3&transport=polling&t=NsGvIgN 的远程资源。(原因: CORS 请求没有成功)"

and

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

在此处输入图像描述

As stated in the console, your browser blocked the connection due to CORS.如控制台所述,由于 CORS,您的浏览器阻止了连接。 Try reading the documentation: https://socket.io/docs/v3/handling-cors/尝试阅读文档: https://socket.io/docs/v3/handling-cors/

or this: (Socket.io + Node.js Cross-Origin Request Blocked)[https://stackoverflow.com/a/38749535/7099900]或者这个:(Socket.io + Node.js 跨域请求被阻止)[https://stackoverflow.com/a/38749535/7099900]

So, I kinda figured it out.所以,我有点想通了。

In the end I end up following another tutorial which is much simpler and much better for the starter.最后,我学习了另一个教程,它对初学者来说更简单、更好。 It's this one .就是这个 Easy to understand, to the point, compact and works with no issues.易于理解,重点突出,结构紧凑且没有问题。

But if you encounter this CORS error then the way to fix it is in another video.但是,如果您遇到此 CORS 错误,那么修复它的方法是在另一个视频中。 Basically you have to install the cors package and add some definitions in the server js code.基本上你必须安装 cors package 并在服务器 js 代码中添加一些定义。 The fix itself is in the 10 minute mark, but I suggest watching from the start.修复本身在 10 分钟内,但我建议从一开始就观看。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM