无法从通过不同服务器或文件系统提供的 html 文件连接到 socket.io

Unable to connect to socket.io from html file served via different server or file system

我正在努力学习 and

大多数在线示例,包括 official one 要求在服务器端设置以下内容:

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
  res.sendfile('index.html');
});

io.on('connection', function(socket){
  console.log('a user connected');
});

http.listen(3000, function(){
  console.log('listening on *:3000');
});

在客户端:

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

所以这使用相同的服务器来为 index.html 提供服务以及处理套接字连接,看起来 在 [=19= 下创建了一个 socket.io js 文件] 服务器上的目录。一切顺利。


现在,我正在开发 应用程序,我现在不必从服务器提供 index 文件,因为它将与应用程序捆绑在一起。我只需要连接到本地机器上特定端口上的套接字服务器 运行。

此外,我不想使用 express,因为我正在学习 - 我认为简单地设置套接字服务器不需要它,我宁愿在不了解它的作用或方式的情况下使用它让我的生活更轻松(换句话说,在进入 jquery... 的世界之前,我宁愿对 javascript 了解一两件事。

所以我在 server.js 文件中尝试了以下内容:

var port = 80;
io = require('socket.io')(port);
console.log('socket server started @ %s !', port);

通过 node server.js 命令执行此命令打印 socket server started @ 80 !

根据 documentation 应该创建一个 http 服务器(可能通过 socket.io 增强了一些很棒的东西)监听端口 80.

现在,如果我通过括号 IDE 在 http://127.0.0.1:56958/...path/index.html 启动的 node.js 服务器加载 index.html,其中包含以下内容:

<script src="scripts/libs/socket.io/socket.io.js"></script>
<script>
    console.log('test');
    var socket = io('http://127.0.0.1:80');
</script>

(其中 scripts/libs/socket.io/socket.io.js 是我从他们的 github repo 下载的独立 sockets.io 客户端库) 这让我在 chrome 的最新版本中出现以下错误:

Refused to execute inline script because it violates the following Content Security Policy directive: "default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'". Either the 'unsafe-inline' keyword, a hash ('sha256-2j6JUXRmZBJXdmMDTRd3ZxygBJNrb8gSbgOi4FOjiy0='), or a nonce ('nonce-...') is required to enable inline execution. Note also that 'script-src' was not explicitly set, so 'default-src' is used as a fallback.

我也试过使用 file:/// 协议从文件系统加载 index.html 文件,这会抛出同样的错误。

我做错了什么,我该如何解决?


注意:我看到了 this 问题,但我没有 cordova.xml 文件,因为我还没有使用 cordova 构建应用程序。我试过启用跨源资源共享(使用商店的扩展),但这也没有帮助。


更新:

目录结构如下:

root
 |_app
 | | // lots of cordova directories and files like package.json
 | |_www
 |  |_scripts
 |  | |_libs
 |  |   |_socket.io
 |  |     |_socket.io.js
 |  |_index.html
 |_node_modules
 | |_socket.io
 |_server
   |_server.js

插件 cordova-plugin-whitelist 阻止了您的 socket.io 连接。您可以查看配置详细信息here。您需要仔细配置它,但出于测试目的,您可以允许所有内容:

<meta http-equiv="Content-Security-Policy" content="default-src *;">