Socket.io 从远程 Cordova 应用程序连接 - 不允许访问

Posted

技术标签:

【中文标题】Socket.io 从远程 Cordova 应用程序连接 - 不允许访问【英文标题】:Socket.io connect from remote Cordova app - not allowed access 【发布时间】:2018-06-13 23:45:57 【问题描述】:

我正在尝试从我的 cordova 应用程序访问 Node.js socket.io 服务器。 然后我收到以下错误:

Failed to load https://www.ride4you.co.il/socket.io/?EIO=3&transport=polling&t=M30S1z4: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://127.0.0.1:8080' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

这是客户端(应用程序或本地主机)的连接代码:

    <script src="https://www.ride4you.co.il/socket.io/socket.io.js">
    </script>
    <script type="text/javascript">
     var socket = io("https://www.ride4you.co.il");
     socket.on("disconnect", function() 
       console.log("Disconnected");
       socket = io();
       console.log("Connected");
     );
    </script>

当我在实际域中尝试此代码时,没有错误,一切正常。但是从不是原始域的应用程序中,有一个块。

我已尝试移除此块,并允许每个源使用 app.js(主 node.js 文件)中的下一个代码访问此套接字:

var express = require('express');
var app = express();
var server = require('http').createServer(app);
global.io = require('socket.io').listen(server);
io.set('origins', '*:*');

但仍然出现同样的错误。

我知道有一个允许特定域的选项,但我正在使用一个没有域的 cordova 应用程序 - 所以我认为每个人都应该允许,不是吗?

谢谢。

【问题讨论】:

【参考方案1】:

在 nodejs 服务器上使用 cors 模块,并在您的 nodejs 服务器上保留此文件的副本 https://www.ride4you.co.il/socket.io/socket.io.js 并从您自己的服务器上请求它

【讨论】:

1.你是什​​么意思保留这个文件的副本? 2. 顺便说一句:当我访问服务器上的 public_html 目录时,我没有看到这个文件,但是当我试图从浏览器访问它时,它就在那里。怎么会?谢谢。 您正在从链接加载库,因此您可以保存在您的存储库中,然后给出该链接的路径 http请求中访问数据没有问题,具体是为了连接socket.io有问题。所以这里的 cors 不是我认为的解决方案。【参考方案2】:

独立于 node.js 细节(参见 Hemant Rajpoot 的回答)这与请求经过身份验证(客户端)这一事实有关。

请检查这个基于 C#+angluar 的 *** 答案,否则显示相同的行为/根本原因:

CORS: credentials mode is 'include'

【讨论】:

以上是关于Socket.io 从远程 Cordova 应用程序连接 - 不允许访问的主要内容,如果未能解决你的问题,请参考以下文章

在本机 iOS 应用程序中通过 socket.io 进行远程程序调用?

通过Node.js和Socket.io来实现手机的远程控制

用于 Apache Cordova 的 VS 2015 工具 - iOS 远程构建不使用 buildServer

Cordova - 从远程 HTML 访问设备功能

Cordova 5.3.1 和 iOS9 平台 - 我无法从外部源加载图像和脚本

当远程但不是本地时,Socket.io 退回到 nginx 代理后面的轮询(websocket 给出 400)