【笔记】ElysiaJS学习笔记

前言

Ergonomic Framework for Humans(官网

创建项目

Bun

1
bun create elysia <project_name>

创建Web服务区

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// 引入模块
import { Elysia } from "elysia";

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

// 创建对象
const app = new Elysia();

// 定义路由,处理请求
app.get("/", (ctx) => {
// 接收请求,返回响应
return "";
});

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

请求

获取请求参数

query

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

path

request
1
GET http://127.0.0.1:80/1
1
2
3
4
app.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
app.post("/", (ctx) => {
const body = ctx.body;
console.log(body.id); // "1"
});

响应

设置响应状态码

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

设置响应头

1
2
3
4
5
6
7
app.get("/", (ctx) => {
return "{}";
}, {
headers: {
"Content-Type": "application/json"
}
});

设置响应体

1
2
3
app.get("/", (ctx) => {
return "";
});

自定义属性

1
2
3
4
app.decorate("key", "value")
app.get("/", (ctx) => {
console.log(ctx.key); // "value"
});

全局状态

1
2
3
4
app.state({})
app.get("/", (ctx) => {
console.log(ctx.store); // {}
});

中间件

1
2
3
4
5
// 定义中间件
const plugin = new Elysia();

// 注册中间件
app.use(plugin);

路由组

1
2
3
4
5
6
7
8
9
app.group("/v1", app => app
.get("/", (ctx) => {})
.group("/user", app => app
.get("/", (ctx) => {})
)
.group("/product", app => app
.get("/", (ctx) => {})
)
)

完成

参考文献

哔哩哔哩——_优雅先森