【笔记】Deno的Web服务器

前言

Deno通过oak模块实现Web服务器

创建Web服务器

80:指定端口号

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// 引入模块
import { Application, Router } from "https://deno.land/x/oak/mod.ts"

// 定义端口号
const port = 80;

// 创建对象
const app = new Application();
const router = new Router();

// 定义中间件
app.use(router.routes()); // 定义路由中间件
app.use(router.allowedMethods()); // 允许任何请求方式

// 定义路由,处理请求
router.get("/", (context) => {
// 接收请求,返回响应
context.response.body = "";
});

// 绑定端口,启动服务器
await app.listen({ port });
console.log(`http://127.0.0.1:${port}`);

处理请求

获取请求行

获取请求URL

1
const path = context.request.url.pathname;

获取请求参数

query

1
2
3
router.get("/", (context) => {
const query = context.request.url.searchParams;
});

body

1
2
3
router.post("/", (context) => {
const body = await context.request.body();
});

path

1
2
3
router.get("/:id", (context) => {
const path = context.params;
});

处理响应

设置响应行

设置响应状态码

1
2
3
router.get("/", (context) => {
context.response.status = 200;
});

设置响应头

1
2
3
router.get("/", (context) => {
context.response.headers.set("<key>", "<value>");
});

设置响应体

1
2
3
router.get("/", (context) => {
context.response.body = "";
});

路由

多个路由

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
router.post("/", (context) => {
context.response.body = "";
});

router.delete("/:id", (context) => {
context.response.body = "";
});

router.put("/", (context) => {
context.response.body = "";
});

router.get("/:id", (context) => {
context.response.body = "";
});

router.get("/", (context) => {
context.response.body = "";
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
router
.post("/", (context) => {
context.response.body = "";
})
.delete("/:id", (context) => {
context.response.body = "";
})
.put("/", (context) => {
context.response.body = "";
})
.get("/:id", (context) => {
context.response.body = "";
})
.get("/", (context) => {
context.response.body = "";
});

完成

参考文献

哔哩哔哩——程序员吴海洋