Deno Typescript 找不到服务器依赖注入

时间:2021-03-03 22:24:16

标签: typescript dependency-injection deno

我目前正在试验 Deno 及其测试功能。我想构建一个本地服务器并将标准库中的服务函数注入我的类。目前,我运行 deno test --allow-all 并收到错误:

error: TS2304 [ERROR]: Cannot find name 'Server'.
  runningServer: Server;

我遵循了 Deno 手册中的模式建议,将我的导入移动到 deps.ts

deps.ts

export { assertEquals } from "https://deno.land/std/testing/asserts.ts";

export { serve } from "https://deno.land/std@0.88.0/http/server.ts";

main.ts

import { assertEquals, serve } from "./deps.ts";
import { localServer } from "./local_server.ts";

Deno.test("can query a local server", async () => {
  const ls = new localServer("Hello World!", 8000, serve);
  ls.listen();
  const request = await fetch("http://0.0.0.0:8000/");
  const response = await request.text();
  assertEquals(response, "Hello World!");
  ls.destroy();
});

local_server.ts

class localServer {
  runningServer: Server;
  response: string;
  port: number;
  constructor(
    response: string,
    port: number,
    makeServer: {
      (addr: string | Pick<Deno.ListenOptions, "port" | "hostname">): Server;
      (arg0: { port: number }): Server;
    },
  ) {
    this.response = response;
    this.port = port;
    this.runningServer = makeServer({ port: this.port });
  }

  async listen() {
    const body = this.response;
    for await (const req of this.runningServer) {
      req.respond({ body });
    }
  }

  destroy() {
    this.runningServer.close();
  }
}

export { localServer };

1 个答案:

答案 0 :(得分:0)

问题很可能是fetch("http://0.0.0.0:8000/")。我猜你填写了那个 IP 地址,因为服务器在日志中报告它是 listening on 0.0.0.0。这并不意味着您可以在该地址上查询它,0.0.0.0 是任何 IPv4 地址的占位符,因此不是用于查询的有效 IP 地址。

使用 localhost::1127.0.0.1 或其他有效的 IP 地址或主机名。

相关问题