7.7 Deno HTTP Web服务器

2021-07-05  本文已影响0人  9e8aeff1c70c

概念

概览

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

ℹ️ 原生的HTTP服务器目前不稳定,这意味着API还没有定稿,在未来版本的Deno中可能会发生破坏性的变化。要让这里讨论的API可用,您必须使用--unstable标志运行deno。

web server例子

在此示例中,客户端的用户代理返回给客户端:

webserver.ts:

// Start listening on port 8080 of localhost.
const server = Deno.listen({ port: 8080 });
console.log(`HTTP webserver running.  Access it at:  http://localhost:8080/`);

// Connections to the server will be yielded up as an async iterable.
for await (const conn of server) {
  // In order to not be blocking, we need to handle each connection individually
  // in its own async function.
  (async () => {
    // This "upgrades" a network connection into an HTTP connection.
    const httpConn = Deno.serveHttp(conn);
    // Each request sent over the HTTP connection will be yielded as an async
    // iterator from the HTTP connection.
    for await (const requestEvent of httpConn) {
      // The native HTTP server uses the web standard `Request` and `Response`
      // objects.
      const body = `Your user-agent is:\n\n${requestEvent.request.headers.get(
        "user-agent",
      ) ?? "Unknown"}`;
      // The requestEvent's `.respondWith()` method is how we send the response
      // back to the client.
      requestEvent.respondWith(
        new Response(body, {
          status: 200,
        }),
      );
    }
  })();
}

然后运行下面命令:

deno run --allow-net --unstable webserver.ts

然后在浏览器中导航到http://localhost:8080/‘。

使用 std/http

如果您不想使用不稳定的API,您仍然可以使用标准库的HTTP服务器:

webserver.ts:

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

const server = serve({ port: 8080 });
console.log(`HTTP webserver running.  Access it at:  http://localhost:8080/`);

for await (const request of server) {
  let bodyContent = "Your user-agent is:\n\n";
  bodyContent += request.headers.get("user-agent") || "Unknown";

  request.respond({ status: 200, body: bodyContent });
}

然后运行下面的命令:

deno run --allow-net webserver.ts
上一篇下一篇

猜你喜欢

热点阅读