前言
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
request1
| GET http://127.0.0.1:80/1
|
1 2 3 4
| app.get("/:id", (ctx) => { const path = ctx.query; console.log(path["id"]); });
|
path
request1
| GET http://127.0.0.1:80/1
|
1 2 3 4
| app.get("/:id", (ctx) => { const path = ctx.params; console.log(path["id"]); });
|
body
request1 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 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); });
|
全局状态
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) => {}) ) )
|
完成
参考文献
哔哩哔哩——_优雅先森