【笔记】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("/", (ctx) => {
// 接收请求,返回响应
ctx.response.body = "";
});

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

请求

获取资源路径

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

获取请求参数

query

request
1
GET http://127.0.0.1:80/?id=1
1
2
3
4
router.get("/", (ctx) => {
const query = ctx.request.url.searchParams;
console.log(query["id"]); // "1"
});

path

request
1
GET http://127.0.0.1:80/1
1
2
3
4
router.get("/:id", (ctx) => {
const path = ctx.params;
console.log(path["id"]); // "1"
});

body

request
1
2
3
4
5
6
POST http://127.0.0.1:80/
Content-Type: application/json

{
id: "1"
}
1
2
3
4
router.post("/", (ctx) => {
const body = await ctx.request.body();
console.log(body.id); // "1"
});

响应

设置响应状态码

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

设置响应头

1
2
3
router.get("/", (ctx) => {
ctx.response.headers.set("Content-Type", "application/json");
});

设置响应体

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

路由

多个路由

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

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

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

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

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

完成

参考文献

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