json-server
前言:在开发过程中,前后端无论是否分离,接口大多数是滞后于页面开发的,所以我们有必要建立一个REST风格的API接口,给前端页面提供虚拟的数据。
json-server 是使用Node写的一个第三方模块,利用json-server可以搭建一个小型的服务器
(1)安装
在电脑中全局安装json-server(注意:这个模块是基于Node开发的,所以前提是电脑中已经安装了node.js)
npm install json-server -g
(2)运行
第一种情况
假设在你的项目中没有myData.json这个文件,直接在命令行输入 json-server myData.json
,结果像下图所示,会自动在你的项目中生成这么一个文件,并且可以通过 http://localhost:3000/posts
、http://localhost:3000/conments
、http://localhost:3000/profile
去访问这些数据。
第二种情况
在你的项目中有了一个数据文件 叫做 data.json ,文件中有如下内容:
{
"dataList":[
{"id": 0,"name": "user0"},
{"id": 1,"name": "user1"},
{"id": 2,"name": "user2"},
{"id": 3,"name": "user3"}
]
}
那么你就可以直接在命令行输入:json-server data.json --port 3000
(并指定了端口号),我们就可以通过http://localhost:3000/dataList
去访问上面这些数据。
(3)操作数据
1、GET 获取全部数据
在postman中输入http://localhost:3000/dataList
可获得全部数据
2、GET获取单个数据
给http://localhost:3000/dataList/2
或者 http://localhost:3000/dataList?id=2
可以指定获取具体对应的那条数据
3、POST 上传数据 (id是可以自增的)
4、DELETE删除数据
5、PUT 修改某一条数据
http://localhost:3000/dataList/3
必须加条件
6、GET 模糊查询 xxx_like
使用put将数据改成如下,有相同的部分
使用 http://localhost:3000/dataList?name_like=999
即可以模糊匹配name中带有999的数据