首页 > 解决方案 > Deno Typescript 找不到服务器依赖注入

问题描述

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

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

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

部门.ts

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

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

主要的.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 };

标签: typescriptdependency-injectiondeno

解决方案


这个问题很可能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 地址或主机名。


推荐阅读