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

我正在尝试学习node.js和socket.io 。

网上的大部分例子,包括官方的例子都要求在服务器端设置以下内容:

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以及处理套接字连接,并且看起来像sockets.io在服务器上的socket.io目录下创build了一个socket.io js文件。 所有这一切都很好。


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

此外,我不想使用快递,因为我正在学习 – 我不认为这是简单地设置一个套接字服务器的必要条件,我不使用它不理解它是什么或如何使我的生活更容易换句话说, 在跳入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 !

根据文档 ,应该创build一个http服务器( 可能增强了socket.io与真棒的东西 )听80端口。

现在,如果我通过由http://127.0.0.1:56958/...path/index.html中括号IDE启动的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文件,这会引发相同的错误。

我做错了什么,我该如何解决这个问题?


注:我已经看到了这个问题,但我没有cordova.xml文件,因为我没有使用cordova来构build应用程序。 我试过启用跨来源资源共享( 使用从商店扩展 ),但是也没有帮助。


更新:

以下是目录结构:

 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连接。 你可以在这里查看configuration细节。 你会仔细configuration它,但为了testing的目的,你可以允许一切:

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