介绍说明
想象一下,在没有后端支持的情况下,仅用 30 秒就能创建并运行你的 API 模拟服务。这不是魔法,这是 json-server,一款轻量级、易于使用的接口模拟工具。通过简单的 json 文件,你可以快速搭建起模拟接口,极大地促进了项目初期的前后端协同开发。
安装运行
为了方便演示,将使用 docker 的方式来安装运行 json-server。
- 准备 Dockerfile
FROM node:19-alpine
RUN npm install -g json-server --registry=https://registry.npmmirror.com
CMD ["json-server", "--host", "0.0.0.0", "--watch", "/app/db.json"]
- 构建 docker 镜像
在 Dockerfile 所在目录执行以下指令:
docker build -t json-server:latest -f ./Dockerfile .
docker images | grep json-server
- 准备 db.json
{
"posts": [
{ "id": "1", "title": "a title" },
{ "id": "2", "title": "another title" }
],
"comments": [
{ "id": "1", "text": "a comment about post 1", "postId": "1" },
{ "id": "2", "text": "another comment about post 1", "postId": "1" }
]
}
- 运行 json-server
docker rm -f json-server
docker run --name json-server -d \
-v ${PWD}/db.json:/app/db.json \
-p 3000:3000 \
json-server:latest
docker ps | grep json-server
使用简介
- 获取列表
curl http://localhost:3000/posts
- 通过 Id 获取记录
curl http://localhost:3000/posts/1
- 按条件筛选,支持 AND 和 OR 操作
curl "http://localhost:3000/posts?id=1"
# AND 操作
curl "http://localhost:3000/posts?id=1&title=title"
# OR 操作
curl "http://localhost:3000/posts?id=1&id=2"
- 分页,_page 表示页面,从 1 开始,_limit 表示每页显示条数
curl "http://localhost:3000/posts?_page=1&_limit=1"
curl "http://localhost:3000/posts?_page=2&_limit=1"
- 排序
curl "http://localhost:3000/posts?_sort=id&_order=asc"
curl "http://localhost:3000/posts?_sort=id&_order=desc"
- 字段比较,当前仅支持 _gte,_lte 和 _ne
curl "http://localhost:3000/posts?id_lte=1"
curl "http://localhost:3000/posts?id_gte=2"
curl "http://localhost:3000/posts?id_ne=2"
- 获取 db 数据,即 db.json 的所有数据
curl http://localhost:3000/db
项目地址
更多项目详细信息请到项目主页获取
快捷镜像
ccr.ccs.tencentyun.com/erik_xu/json-server:latest
写在最后
这就是 json-server 的强大之处,一个简单但强大的工具,能够为你的开发过程带来前所未有的便利。如果你对今天的分享有任何疑问,或者有更多技术见解和开源工具推荐,别忘了在【跬步之巅】公众号下留言。我们一起探索技术的无限可能,让每一步都充满发现的喜悦。