这里跳过node安装以及npm安装
- 先全局安装:npm install json-server -g
- 在桌面创建一个空的文件夹JSONSERVER
- cd 进入到这个文件夹执行npm init --yes,这时候文件夹会多出一个package.json的文件
- 项目再安装一次:npm install json-server --save
-
修改启动命令,把package.json里的这行 "test": "echo \"Error: no test specified\" && exit 1" 替换成 "json:server": "json-server --watch db.json"方便每一次的启动
- 再文件夹根目录下新建一个db文件命名为user.db,复制下面的测试数据到里面
{"user":[{"name":"Henry","phone":"333-444-555","email":"henry@gmail.com","id":1,"age":30,"companyId":1},{"name":"Bucky","phone":"333-444-555","email":"Bucky@gmail.com","id":2,"age":30,"companyId":2},{"name":"Emily","phone":"333-444-555","email":"Emily@gmail.com","id":3,"age":30,"companyId":3},{"name":"Llyse","phone":"333-444-555","email":"Llyse@gmail.com","id":4,"age":30,"companyId":3}],"companies":[{"id":1,"name":"Apple","description":"Apple is good!"},{"id":2,"name":"Microsoft","description":"Microsoft is good!"},{"id":3,"name":"Google","description":"Google is good!"}]
}
最后,在此文件夹的终端启动json-server,命令为:npm run json:server
提示:
//获取所有用户信息 http://localhost:3000/users
//获取id为1的用户信息 http://localhost:3000/users/1
//获取公司的所有信息 http://localhost:3000/companies
//获取单个公司的信息 http://localhost:3000/companies/1
//获取用户和公司的相关联信息 http://localhost:3000/companies/3/users
//根据公司名字获取信息 http://localhost:3000/companies?name=Microsoft
//根据多个名字获取公司信息 http://localhost:3000/companies?name=Microsoft&name=Apple
//根据多个名字获取公司信息 http://localhost:3000/companies?_page=1&_limit=2
//根据升序排序 http://localhost:3000/companies?_sort=name&_order=asc //降序是desc
//获取年龄30以上的 http://localhost:3000/users?age_gte=30
//获取年龄30 - 40的 http://localhost:3000/users?age_gte=30&age_lte=40
//搜索用户信息 http://localhost:3000/users?q=k
扩展:(如果想要在本地使用jsonholder里面的数据,在package.json加上红色框的内容)
源码:
"json:server:remote": "json-server http://jsonplaceholder.typicode.com/db"