json-server
- json-server 底层使用了一个名为 lowdb JSON 数据库,这个数据库同样可以用于 Node、Electron、Broswer 等环境下。
- 对 json-server 中数据的增、删、改等操作,都会被 json-server 持久化于 json 文件。
基本使用
1. 安装
# 全局安装
npm i json-server -g
2. 创建json文件
以创建 db.json 文件为例:
{
"posts": [
{ "id": 1, "title": "json-server", "author": "typicode" }
],
"comments": [
{ "id": 1, "body": "some comment", "postId": 1 }
],
"profile": { "name": "typicode" }
}
db.json 文件相当于创建了三个数据库表:posts
、comments
、profile
,而且数据库表的默认主键为 id
。
3. 启动 json-server
json-server --watch db.json
默认监听 3000 端口。
4. 请求数据
以请求 posts
表中数据为例:
GET 获取数据
GET 请求 | 请求内容 |
---|---|
http://localhost:3000/posts | 获取 posts 中的所有数据 |
http://localhost:3000/posts/1 | 获取 posts 中id为1的数据 |
POST 添加数据
使用 Postman 工具示例,在实际项目中可以使用 axios
、fetch
等代替。
PATCH 修改数据
将 id=3
的 title 修改为 json-server-change-3
。
- 使用
PATCH
请求方式 - 使用 RESTful API 样式
DELETE 删除数据
将 id=3
的数据删除。
根据条件查询数据
进阶用法
未完待续
参考:
[1]. json-server基本使用
[2]. json-server 详解
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。