Deno尝鲜(2)-创建一个http服务器

serve源码

/**
 * Create a HTTP server ------>创建一个http服务器
 *
 *     import { serve } from "https://deno.land/std/http/server.ts";
 *     const body = "Hello World\n";
 *     const s = serve({ port: 8000 });
 *     for await (const req of s) {
 *       req.respond({ body });
 *     }
 */
export function serve(addr: string | HTTPOptions): Server {
  if (typeof addr === "string") {
    const [hostname, port] = addr.split(":");
    addr = { hostname, port: Number(port) };
  }

  const listener = listen(addr);
  return new Server(listener);
}

获取请求的地址

如下所示

import { serve } from "https://deno.land/[email protected]/http/server.ts";
const s = serve({ port: 8000 });
console.log("http://localhost:8000/");
for await (const req of s) {
  console.log(req.url)
  console.log(req.method)
  req.respond({ body: "Hello Worldjdaj\n" });
}

req上可以获得的参数
Deno尝鲜(2)-创建一个http服务器_第1张图片
http://localhost:8000/test?id=1输入该请求信息
req.url : /test?id=1
req.method: GET

你可能感兴趣的:(Deno)