【问题标题】:Serving files on a local network with Deno使用 Deno 在本地网络上提供文件
【发布时间】:2020-08-17 08:35:28
【问题描述】:

我最近决定试一试Deno

现在我正在尝试在我的本地网络上设置一个基本文件服务器,但它只会将文件提供给我的计算机而不是网络的其余部分(我什至无法从在我的电脑之外)。对于我的一生,我无法弄清楚为什么它只能在本地工作。

为了以防万一,我在下面添加了我现在正在使用的代码,但我很确定问题出在其他地方,因为我在使用 this file_server example 以及使用 @ 创建文件服务器时遇到了同样的问题987654323@

import { serve } from 'https://deno.land/std@v0.42.0/http/server.ts';
const server = serve({ port: 3000 });

const decoder = new TextDecoder('utf-8');

for await (const req of server) {
    const filePath = 'public' + req.url;

    try {
        const data = await Deno.readFile(filePath);
        req.respond({ body: decoder.decode(data) });
    } catch (error) {
        if (error.name === Deno.errors.NotFound.name) {
            console.log('File "' + filePath + '" not found');
            req.respond({ status: 404, body: 'File not found' });
        } else {
            req.respond({ status: 500, body: 'Rest in pieces' });
            throw error;
        }
    }
}

我用来运行文件的命令是:

deno --allow-all server.ts

当我在 Node.js 中创建一个简单的文件服务器时,一切正常。它可以向我的计算机和网络上的任何其他设备提供文件。

我认为问题在于我对 Deno 及其安全概念的理解,但我不知道。如果需要,我将非常感谢任何帮助,并可以提供更多详细信息。

【问题讨论】:

标签: http localhost deno


【解决方案1】:

您需要将主机名绑定到0.0.0.0,如下所示:

const server = serve({ hostname: '0.0.0.0', port: 3000 });

默认情况下,您的网络服务器只响应localhost127.0.0.1

绑定到0.0.0.0 告诉 Deno 绑定到你机器上的所有 IP 地址/接口。这使得您网络上的任何机器都可以访问它。

192.168.x.y. 格式的网络 IP 地址也会绑定到 Deno 网络服务器,这允许网络中的另一台计算机使用您的本地 IP 地址访问网络服务器。

【讨论】:

  • 很好,效果很好。问题似乎是我对网络概念的有限掌握......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-31
  • 1970-01-01
  • 2016-07-28
相关资源
最近更新 更多