JSON API 实战
这一节实现一个内存版文章 API,用来串联路由、请求体、状态码和统一响应。
数据结构
type Post = {
id: string
title: string
content: string
createdAt: string
}
const posts = new Map<string, Post>()
创建应用
import { Hono } from 'hono'
const app = new Hono()
app.get('/posts', (c) => {
return c.json({
data: Array.from(posts.values()),
})
})
查询详情
app.get('/posts/:id', (c) => {
const post = posts.get(c.req.param('id'))
if (!post) {
return c.json({ message: 'Post not found' }, 404)
}
return c.json({ data: post })
})
创建文章
app.post('/posts', async (c) => {
const body = await c.req.json<{
title?: string
content?: string
}>()
if (!body.title || !body.content) {
return c.json({ message: 'title and content are required' }, 400)
}
const post: Post = {
id: crypto.randomUUID(),
title: body.title,
content: body.content,
createdAt: new Date().toISOString(),
}
posts.set(post.id, post)
return c.json({ data: post }, 201)
})
更新文章
app.put('/posts/:id', async (c) => {
const id = c.req.param('id')
const post = posts.get(id)
if (!post) {
return c.json({ message: 'Post not found' }, 404)
}
const body = await c.req.json<{
title?: string
content?: string
}>()
const nextPost: Post = {
...post,
title: body.title ?? post.title,
content: body.content ?? post.content,
}
posts.set(id, nextPost)
return c.json({ data: nextPost })
})
删除文章
app.delete('/posts/:id', (c) => {
const id = c.req.param('id')
if (!posts.has(id)) {
return c.json({ message: 'Post not found' }, 404)
}
posts.delete(id)
return c.body(null, 204)
})
测试请求
curl -X POST http://localhost:3000/posts \
-H "Content-Type: application/json" \
-d '{"title":"Hono","content":"Hello API"}'
curl http://localhost:3000/posts
下一步改进
这个示例使用内存存储,重启后数据会丢失。真实项目需要:
- 使用数据库保存数据。
- 用 Zod 或其他验证器检查输入。
- 增加分页、排序和筛选。
- 增加鉴权和权限控制。
- 为接口补充测试。
相关内容
- Hono 是什么 介绍 Hono 的定位、核心特点、Web Standards 思路、多运行时能力,以及它与传统 Node.js Web 框架的差异。
- 安装和 Hello World 学习使用 create-hono 创建 Hono 项目,分别了解通用模板和 Node.js 模板的 Hello World 写法。
- 运行时选择 对比 Hono 在 Node.js、Cloudflare Workers、Bun、Deno 等运行时中的入口写法、部署方式和适用场景。
- 路由基础 学习 Hono 的 GET、POST、动态参数、通配符、路由分组和模块化路由写法。
- Context 详解 介绍 Hono Context 的 req、json、text、html、redirect、header、status、set、get 等常用 API。
- 中间件机制 学习 Hono 中间件的执行顺序、自定义中间件写法、路径匹配、next 调用和常见使用场景。