本页内容

简单 HTTP Web 服务器

概念 跳转到标题

  • 使用 Deno 集成的 HTTP 服务器运行您自己的 Web 服务器。

概述 跳转到标题

只需几行代码,您就可以运行自己的 HTTP Web 服务器,并控制响应状态、请求头等。

server.ts
const port = 8080;

const handler = (request: Request): Response => {
  const body = `Your user-agent is:\n\n${
    request.headers.get("user-agent") ?? "Unknown"
  }`;

  return new Response(body, { status: 200 });
};

console.log(`HTTP server running. Access it at: http://localhost:8080/`);
Deno.serve({ port }, handler);

然后使用以下命令运行:

deno run --allow-net server.ts