1-5 json-server常规mock功能+静态资源服务器
常规 CRUD 操作
查询
# 获取所有
GET /posts
# 条件查询
GET /posts?author=张三
# 分页(默认每页10条)
GET /posts?_page=2&_limit=5
# 排序
GET /posts?_sort=id&_order=desc
# 范围查询
GET /posts?id_gte=5&id_lte=10
# 模糊搜索
GET /posts?title_like=关键词
bash
新增
POST /posts
Content-Type: application/json
{ "title": "新文章", "author": "王五" }
bash
id 会自动递增。数据直接写入 db.json 文件。
更新
PUT /posts/1
Content-Type: application/json
{ "title": "更新后的标题", "author": "张三" }
bash
删除
DELETE /posts/1
bash
静态资源服务器
json-server 可以同时作为静态文件服务器:
# 在项目目录下创建 public 文件夹
mkdir public
# 放入静态文件
echo '<h1>Hello</h1>' > public/index.html
# 启动时自动托管 public 目录
json-server db.json
bash
访问 http://localhost:3000/ 即可看到静态页面。适合用作示例站点的静态资源托管。
自定义配置
# 指定端口
json-server db.json --port 3001
# 指定静态目录
json-server db.json --static ./public
# 使用自定义路由
json-server db.json --routes routes.json
bash
路由配置示例:
{
"/api/*": "/$1",
"/posts/:id/show": "/posts/:id"
}
json
关联查询
# 包含关联数据
GET /posts/1?_embed=comments
# 包含父级数据
GET /comments?_expand=post
bash
参考资源
- json-server 完整文档 - 官方 GitHub
↑