如何使用json-server
·
json-server 是一个能让你30 秒内零代码搭出模拟 REST API 的工具,特别适合后端接口还没写好时,前端先拿来测试。
1.全局安装:确保装了 Node.js(版本要 12 以上),然后执行
npm install -g json-server
2.创建数据文件:在项目目录下新建一个 db.json,里面直接写假数据就行。
{
"posts": [
{ "id": 1, "title": "json-server 使用指南" }
],
"comments": [
{ "id": 1, "body": "很实用", "postId": 1 }
]
}
3.启动服务:在文件所在目录执行 json-server --watch db.json,默认会在 http://localhost:3000 启动。
4.访问接口:浏览器打开 http://localhost:3000/posts 就能看到数据了。
启动后,json-server 会自动把 db.json 里每个 key 变成一个 RESTful 接口,支持增删改查:
查询(GET):GET /posts 获取所有,GET /posts/1 获取 id 为 1 的那条。
新增(POST):POST /posts,请求体里放要添加的数据,id 会自动生成。
修改(PUT / PATCH):PUT /posts/1 是整体覆盖,PATCH /posts/1 只更新传过来的字段。
删除(DELETE):DELETE /posts/1 删除对应数据。
更多推荐


所有评论(0)