一、json-server 安装,创建数据,启动
安装 json-server
npm install json-server
创建json文件
创建 db.json 来存储数据
{
"users": [
{
"id": 1,
"name": "John",
"age": 18
},
{
"id": 2,
"name": "Anna",
"age": 20
},
{
"id": 3,
"name": "Elsa",
"age": 20
},
{
"id": 4,
"name": "Olaf",
"age": 5
},
{
"id": 5,
"name": "Lisa",
"age": 30
}
]
}
启动 json-server
--port 8080 修改端口号为8080, 默认3000
json-server --watch db.json --port 8080
访问网址 http://localhost:8080
启动成功如图所示
访问网址 http://localhost:8080/users
好,我们的第一阶段就成功了
二、增删查改
我们需要用到apifox或者postman来做接口调试,我这边使用apifox
查看/获取
获取所有用户
新建一个接口,使用GET方法,访问 http://localhost:8080/users
获取个人用户信息
我们通过访问 http://localhost:8080/users/1 来访问id为1的用户个人信息
也可以通过 http://localhost:8080/users?id=1的方式访问
分页查询
通过访问 http://localhost:8080/users?_page=1&_limit=2 来访问第一页的数据(每页展示2条)
模糊查询
通过姓名查询用户
http://localhost:8080/users?name=Lisa
通过姓名模糊查询用户 (在字段后面添加like)
http://localhost:8080/users?name_like=Lisa
增加
POST http://localhost:8080/users
如果没有说明id,json-server会自动补上
(这个地方不应该是username,应该是name,我忘记了,数据库里面没有username这个字段)
修改
注意:需要在路由上说明要修改的用户的id(不能在响应体里写id)
删除
DELETE http://localhost:8080/users/1