deno.com

HTTP server: Routing

在 Github 上编辑

An example of a HTTP server that handles requests with different responses based on the incoming URL.

URL patterns can be used to match request URLs. They can contain named groups that can be used to extract parts of the URL, e.g. the book ID.
const BOOK_ROUTE = new URLPattern({ pathname: "/books/:id" });

function handler(req: Request): Response {
Match the incoming request against the URL patterns.
  const match = BOOK_ROUTE.exec(req.url);
If there is a match, extract the book ID and return a response.
  if (match) {
    const id = match.pathname.groups.id;
    return new Response(`Book ${id}`);
  }
If there is no match, return a 404 response.
  return new Response("Not found (try /books/1)", {
    status: 404,
  });
}
To start the server on the default port, call `Deno.serve` with the handler.
Deno.serve(handler);

使用 Deno CLI 在本地运行 此示例

deno run --allow-net https://docs.denohub.com/examples/scripts/http_server_routing.ts

在 Deno Deploy Playground 中尝试此示例:

Deploy

你找到需要的内容了吗?

隐私政策