【问题标题】:Socket.io connect from remote Cordova app - not allowed accessSocket.io 从远程 Cordova 应用程序连接 - 不允许访问
【发布时间】: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 应用程序 - 所以我认为每个人都应该允许,不是吗?

谢谢。

【问题讨论】:

    标签: node.js socket.io


    【解决方案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 的 stackoverflow 答案,否则显示相同的行为/根本原因:

    CORS: credentials mode is 'include'

    【讨论】:

      猜你喜欢
      • 2013-06-02
      • 2014-03-07
      • 2015-05-23
      • 2013-09-01
      • 1970-01-01
      • 2015-06-02
      • 2012-06-02
      • 1970-01-01
      • 2018-11-12
      相关资源
      最近更新 更多